@ResponseBody
@ResponseBody 将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。
@RequestMapping(params="method=view")
@ResponseBody
public String method(@RequestParam("id") Long id,
HttpServletRequest request,
HttpServletResponse response){
...
return jsonData;
}
如上可以直接返回json字符串。如果不配置@ResponseBody,也可以使用response输出数据然后 return null,达到返回json字符串的效果。
@responsebody表示该方法的返回结果直接写入HTTP response body中
一般在获取数据时使用,在使用 @RequestMapping 后,返回值通常解析为跳转路径,
但是加上 @responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。
比如异步获取json数据,加上 @responsebody后,会直接返回json数据。
@ResponseBody之后返回字符串中中文可能会出现乱码,因为sping mvc默认是text/plain;charset=ISO-8859-1,要支持中需做如下配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>