handler method 参数绑定常用的注解,我们根据他们处理的 Request 的不同内容部分分为四类:
- 处理 requet uri 部分(这里指 uri template 中 variable,不含 queryString 部分)的注解: @PathVariable;
- 处理 request header 部分的注解: @RequestHeader, @CookieValue;
- 处理 request body 部分的注解:@RequestParam, @RequestBody;
- 处理 attribute 类型是注解: @SessionAttributes, @ModelAttribute;
1、 @PathVariable
当使用 @RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的 paramId 可通过 @Pathvariable 注解绑定它传过来的值到方法的参数上。
Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping("/pets/{petId}") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } }
变量名称不一致,需要在 @PathVariable("name")指定 uri template 中的名称。
- @RequestParam
- 因为使用 request.getParameter()方式获取参数,所以可以处理 get 方式中 queryString 的值,也可以处理 post 方式中 body data 的值;
- 用来处理 Content-Type: 为 application/x-www-form-urlencoded 编码的内容,提交方式 GET、POST
- 该注解有两个属性: value、required; value 用来指定要传入值的 id 名称,required 用来指示参数是否必须绑定;
@RequestMapping(value = "/{xx}/xxx", method = RequestMethod.POST) public String msgCallback(@RequestParam(value = "timestamp", required = false) String timestamp, @RequestParam(value = "nonce", required = false) String nonce, @RequestParam(value = "msg_signature", required = false) String msgSignature, @PathVariable String revAppId, HttpServletRequest request, HttpServletResponse response) { return wxMessageHandlerService.messageHandler(request, timestamp, nonce, msgSignature, revAppId); }
- @RequestBody
该注解常用来处理 Content-Type: 不是 application/x-www-form-urlencoded 编码的内容,例如 application/json, application/xml 等;
@RequestMapping(value = "/something", method = RequestMethod.PUT) public void handle(@RequestBody String body, Writer writer) throws IOException { writer.write(body); }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于