【1】在web.xml中处理
这种方式适用于Post中文乱码处理。在web.xml中配置过滤器,这是Springmvc为我们写好的类,可以,通过指定编码格式,从而有效控制Post请求乱码,但是处理不了Get请求方式的乱码
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter>
【2】在Tomcat服务器的配置文件上处理
在~\apache-tomcat-7.0.90\conf\server.xml中处理
打开server.xml,大约在65行左右的位置
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
在Connector中加上URIEncoding="UTF-8"
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
此种方式可以处理,Get与Post请求方式的乱码。配完之后,便不需要在考虑中文乱码的问题
【1】方式一,在@RequestMapping中加上,produces="text/html;charset=utf-8"
@ResponseBody @RequestMapping(value="/test01.action",produces="text/html;charset=utf-8") public String test03() throws Exception { return "我爱你中国"; }
通过,此种方式设置响应编码格式为utf-8。但是,此种方式,意味着,如果需要向页面返回中文,则就需要书写,过于麻烦。所以,请看第二种方式。
【2】方式二、在Springmvc.xml配置文件中书写
<mvc:annotation-driven> <mvc:message-converters> <!-- 处理响应中文内容乱码 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
将上述配置,放入到Springmvc,xml配置文件中,便可以对相应乱码进行全站处理。