@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<Message> findByNickNames(String receiver, Pageable pageable);
ORDER BY ?#{#pageable} 在语句后面加上这个,no why

本文详细解析了Spring MVC中@PathVariable、@RequestParam和@RequestBody等注解的使用方法及区别,通过具体代码示例展示了如何在RESTful API中正确应用这些注解。

被折叠的 条评论
为什么被折叠?



