@PathVariable与@RequestParam与@RequestBody的区别用法
@PathVariable
当使用@RequestMapping URI template 样式映射时,@PathVariable 能使传过来的参数绑定到路由上,这样比较容易写出restful api
@RequestMapping(value="/xxxx/{id}", method=RequestMethod.GET)
public List<Map<String, Object>> getUser(@PathVariable Integer id) {
return userService.getUserById(id);
}
上面这个接口可通过 get 请求 http://xxxxx/1111 来得到想要的数据,1111既是 getUser 的方法参数又是 @RequestMapping 的路由。如果方法参数不想写成和路由一样的应该怎么办?
@RequestMapping(value="/{uid}", method=RequestMethod.GET)
public List<Map<String, Object>> getUser(@PathVariable("uid") Integer id) {
return userService.getUserById(id);
}
在@PathVariable后面接入“uid”就可以了。
@RequestParam
@RequestParam 和 @PathVariable 的区别就在于请求时当前参数是在url路由上还是在请求的body上
@RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestParam(value="phoneNum", required=true) String phoneNum , String userName) { userService.create(phoneNum, userName); return "success"; }
这个接口的请求url这样写:http://xxxxx?phoneNum=xxxxxx,也就是说被 @RequestParam 修饰的参数最后通过 key=value 的形式放在http请求的Body传过来。
@RequestParam与PathVariable区别:
使用 @RequestParam 时,URL是这样的:http://host:port/path?参数名=参数值
使用@PathVariable时,URL是这样的:http://host:port/path/参数值 (用在resultful接口的传参)
@RequestBody
@RequestBody 与 RequestParam区别:
如果为get请求时,后台接收参数的注解应该为RequestParam
如果为post请求时,则后台接收参数的注解就是为RequestBody
@Param
@Param是MyBatis所提供的(org.apache.ibatis.annotations.Param),作为Dao层的注解,作用是用于传递参数,从而可以与SQL中的的字段名相对应,一般在2=<参数数<=5时使用最佳。
ajax传参
如果是普通参数:后台字段名相同接收字段
如果是数组:@RequestParam接收
浙公网安备 33010602011771号