天天看点

@responseBody注解的使用@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"}'

  效果等同于如下代码:

  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">

<!-- 输出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>

</mvc:message-converters>

</mvc:annotation-driven>