Java Web Project中文乱码
之前一段时间都是写英文系统,最近写了几个Demo遇到一些乱码问题,在此总结。
前台乱码
1、JSP显示乱码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
2、前台接收数据时乱码
方案一:设置返回编码
@ResponseBody
@RequestMapping(value="/test/{name}", produces = "text/html;charset=UTF-8")
public String usert(@PathVariable String name){
return name;
}
方案二:重写org.springframework.http.converter.StringHttpMessageConverter
将
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
改成
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
方案三:设置response编码
response.setCharacterEncoding("text/html;charset=UTF-8");
后台乱码
方案一:设置编码拦截器
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
方案二:设置服务器编码
Tomcat 服务器:打开{TomcatDir}/conf/server.xml
在设置端口处
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
改成
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
JBoss EPA EPA 6.X服务器
比如在standalone.xml中之后添加
<system-properties>
<property name="org.apache.catalina.connector.URI_ENCODING" value="UTF-8"/>
<property name="org.apache.catalina.connector.USE_BODY_ENCODING_FOR _QUERY_STRING" value="true"/>
</system-properties>
方案三:设置参数编码
String name = (String) request.getAttribute("name");
name = new String(name.getBytes(), "utf-8");
在不同的场景应使用不同的解决方案。
例如在Spring3.x中,使用Spring编码拦截器会是比较好的选择。
然而在Spring4.x版本中,Spring编码拦截器不会起到效果,需要设置服务器编码,重写StringHttpMessageConverter。
有其他经验的码友可以留言交流一下。