@responseBody注解的使用
2017-09-23 14:51
351 查看
@responseBody注解的使用
1、@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML
数据,是json还是xml根据springmvc配置返回如下,需要注意的呢,在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
2、
@RequestMapping("/login")
@ResponseBody
public User login(User user){
return user;
}
User字段:userName pwd
那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代码:
@RequestMapping("/login")
public void login(User user, HttpServletResponse response){
response.getWriter.write(JSONObject.fromObject(user).toString());
}
spring-mvc.xml配置
<!--扫描配置 -->
<context:component-scan base-package="com.sudytech.**.controller" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!--先进行string转换,防止响应字符串时多加 '"',顺序不能变,必须放在json之前 -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" >
<constructor-arg value="UTF-8"/>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="charset" value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!-- 输出key时是否使用双引号 -->
<value>QuoteFieldNames</value>
<!-- 是否输出值为null的字段 -->
<!-- <value>WriteMapNullValue</value> -->
<!-- 数值字段如果为null,输出为0,而非null -->
<value>WriteNullNumberAsZero</value>
<!-- List字段如果为null,输出为[],而非null -->
<value>WriteNullListAsEmpty</value>
<!-- 字符类型字段如果为null,输出为"",而非null -->
<value>WriteNullStringAsEmpty</value>
<!-- Boolean字段如果为null,输出为false,而非null -->
<value>WriteNullBooleanAsFalse</value>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
相关文章推荐
- 使用springMVC的requestBody和responseBody注解问题
- Spring 注解的使用 @ResponseBody,@RequestBody
- SpringMVC中使用jackson,注解@ResponseBody返回中文乱码问题
- SpringMVC4使用@ResponseBody注解实现JSON自动转换错误
- 使用springMVC注解@ResponseBody与jackson工具类在ajax请求中实现对象与json之间的相互转化
- SpringMVC使用@ResponseBody注解返回中文字符串乱码的问题
- @responseBody注解的使用
- springmvc使用@ResponseBody注解返回对象
- spring mvc 自定义注解ResponseEncryptBody、RequestDecryptBody统一处理加密、解密数据,供移动端使用的rest服务
- 实现SpringMVC中使用@Responsebody注解返回任意POJO对象转换成JSON
- SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(上)
- spring mvc 使用@ResponseBody注解返回json字符串
- @responseBody注解的使用
- SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(上)
- controller中使用@ResponseBody注解,返回数据时出现中文乱码
- 关于spring mvc3的注解之@ResponseBody的使用
- SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(下)
- Spring MVC 中的 @ResponseBody 注解的使用场合
- @responseBody注解的使用
- SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(下)