@RequestRequestBody 注解抛出异常信息 “Required request body is missing”
采用 SSM 框架,前端将参数传递给后端,SpringMVC 可以通过注解 @RequestBody 将传递参数绑定在 Controller 的方法参数中。此时必须注意,当请求方法声明为 GET 和 DELETE 的时候,HTTP 请求规范里规定是不会有 RequestBody 的,只有请求方法声明为 POST 和 PUT 的时候才有,因此 @RequestBody 不适用于 GET 与 DELETE 方法。还有如果请求方法声明为 GET、DELETE,那么 SpringMVC 可以直接将传递参数绑定在方法的参数中,如果请求方法声明为 POST、PUT,则必须使用注解 @RequestBody 修饰 Controller 中的方法参数,否则无法获取前端传递过来的参数值。正确的使用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @Controller @RequestMapping("/user/api") public class UserApiController {
@Autowired private UserApiService userApiService;
@ResponseBody @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) public RequestResult<UserApiVo> getById(@PathVariable("id") int id) { return userApiService.get(id); }
@ResponseBody @RequestMapping(value = "/query", method = RequestMethod.GET) public RequestResult<Page> query(Page page) { return userApiService.query(page); }
@ResponseBody @RequestMapping(value = "/add", method = RequestMethod.POST) public RequestResult add(@RequestBody @Valid UserApiVo vo) { return userApiService.add(vo); }
@ResponseBody @RequestMapping(value = ("/update"), method = RequestMethod.POST) public RequestResult update(@RequestBody @Valid UserApiVo vo) { return userApiService.update(vo); }
@ResponseBody @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public RequestResult delete(@PathVariable("id") int id) { return userApiService.delete(id); }
}
|