@PathVariable与@RequestParam与@RequestBody注解的区别和用法

@PathVariable
Spring3.0 新增的功能
当使用@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传过来,对比下上面的@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接受

jpa的分页查询
异常信息:
Caused by: org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException: Cannot use native queries with dynamic sorting and/or pagination in method public abstract org.springframework.data.domain.Page

解决方案:
@Query(value = “select * from message where receiver = ?1 ORDER BY ?#{#pageable}”,nativeQuery = true)//根据名字查所有
Page findByNickNames(String receiver, Pageable pageable);

ORDER BY ?#{#pageable} 在语句后面加上这个,no why
————————————————
版权声明:本文为CSDN博主「小怪兽AAA」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/PAN17610011759/article/details/89513315

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值