spring mvc配置文件当中添加如下内容,实现responsebody返回String的编码设置,
并且使用fastjson作为json解析器,自动解析java对象作为返回:
<!-- 默认的注解映射的支持,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -->
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters register-defaults="true">
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<!-- 配置Fastjson支持 -->
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="charset" value="UTF-8" />
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
<value>WriteDateUseDateFormat</value>
<value>WriteEnumUsingToString</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<property name="favorPathExtension" value="true" />
</bean>
本文介绍如何在SpringMVC中配置响应体返回String的编码为UTF-8,并使用fastjson作为JSON解析器,自动解析Java对象作为返回内容。通过配置StringHttpMessageConverter解决@ResponseBody的乱码问题,同时配置FastJsonHttpMessageConverter支持Fastjson。
603

被折叠的 条评论
为什么被折叠?



