第一种:通过@RequestBody,直接将请求体映射到对象
1 //@RequestBody 2 @RequestMapping(value = "addUser", method = {RequestMethod.GET, RequestMethod.POST}) 3 public @ResponseBody 4 String addUser(HttpServletRequest request, @RequestBody User user) { 5 logger.debug(request.getRemoteAddr()); 6 return userServices.addUser(user); 7 }
请求:
响应:
第二种:通过@RequestBody,获取请求头部字段
1 //@RequestHeader 2 @RequestMapping(value = "addUser/header", method = {RequestMethod.GET, RequestMethod.POST}) 3 public @ResponseBody 4 String addUser_header(HttpServletRequest request, @RequestBody User user,@RequestHeader("Accept-Encoding") String encoding,@RequestHeader("Content-Type") String type) { 5 logger.debug(request.getRemoteAddr()); 6 logger.debug("Accept-Encoding:{}",encoding); 7 logger.debug("Content-Type:{}",type); 8 return userServices.addUser(user); 9 }
日志:
第三种:通过@PathVariable,获取url template 里的参数
1 //@PathVariable 2 @RequestMapping(value = "addUser/{name}/{age}", method = {RequestMethod.GET, RequestMethod.POST}) 3 public @ResponseBody 4 String addUser_path(HttpServletRequest request, @PathVariable("name") String name, @PathVariable("age") String age) { 5 logger.debug(request.getRemoteAddr()); 6 User user = new User(); 7 user.setAge(age); 8 user.setName(name); 9 return userServices.addUser(user); 10 }
请求:
响应:
第四种:通过@RequestParam,获取请求参数
1 //@RequestParam 2 @RequestMapping(value = "addUser_param", method = {RequestMethod.GET, RequestMethod.POST}) 3 public @ResponseBody 4 String addUser_params(HttpServletRequest request, @RequestParam("name") String name, @RequestParam("age") String age) { 5 logger.debug(request.getRemoteAddr()); 6 User user2 = new User(); 7 user2.setAge(age); 8 user2.setName(name); 9 return userServices.addUser(user2); 10 }
请求1:post请求
请求2:get请求
源码地址:
https://github.com/huangchunhao/mockdemo