基于spring-boot的测试桩设计--几种常见的controller
第一种:通过@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,获取请求参数。(注意,请求头部中的Content-Type一定是application/x-www-form-urlencoded)
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请求(parameter)
请求2:post请求(body)
请求3:get请求(post也可以)
源码地址:
https://github.com/yuesest/mockdemo
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/11380561.html