后端如何获取前端的参数
@RequestParam 和 @PathVariable 注解是用于从 request 中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam 是从 request 里面拿取值,而 @PathVariable 是从一个URI模板里面来填充
@PathVariable
通过URL模版来填充
@RequestMapping(value = "/getbyid/{id}", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getbyid( HttpServletRequest request,@PathVariable("id") int id){
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("id", id);
return modelMap;
}
当访问:http://localhost:8080/getbyid/1可以直接获取id=1
@PathParam
@RequestMapping(value = "/getbyid", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getbyid( HttpServletRequest request,@RequestParam(value="id")int id){
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("id", id);
return modelMap;
}
当访问:http://localhost:8080/getbyid?id=2可以直接获取id=2
总结
如果只是 ID 这种单个或者多个数字字母,使用 @PathVariable 是非常好的选择,但是如果是获取多个参数,而且是不同类型的,那么最好使用 @PathParam。