使用@RequestBody注解映射request body
方法参数注解@RequestBody表明方法参数将被绑定到HTTP请求体中。例如
@RequestMapping(value="/something", method=RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException{
writer.write(body);
}
使用HttpMessageConverter将请求体转换为方法参数。HttpMessageConverter负责将HTTP请求信息转换成对象,将对象转换成HTTP响应体。RequestMappingHandlerAdapter使用默认的HttpMessageConverters支持@RequestBody注解。
ByteArrayHttpMessageConverter转换字节数组。
StringHttpMessageConverter转换字符串。
FormHttpMessageConverter转换表单数据。
SourceHttpMessageConverter转换javax.xml.transform.Source。
一个@RequestBody方法参数可以使用@Valid注解,这样将使用已配置的Validator实体校验。
类似于使用@ModelAttribute参数,Errors argument可以被用作检查错误。如果argument没有声明,将会产生MethodArgumentNotValidException。该异常由DefaultHandlerExceptionResolver处理,返回客户端404错误。
使用@ResponseBody注解映射响应体
@ResponseBody注解类似于@RequestBody。该注解表示方法的返回类型是直接写到HTTP响应体中。示例
@RequestMapping(value="/something", method=RequestMethod.PUT)
@ResponseBody
public String helloWorld(){
retrun "Hello World";
以上示例中结果文本Hello World将直接写到响应流中。
对于@RequestNody,Spring使用HttpMessageConverter将返回对象转换到响应体中。