中文乱码的几种情况:
页面乱码、action乱码、数据库乱码、国际化乱码
解决方法如下:
1.将所有jsp页面设置为utf-8编码
<%@ page contentType=”text/html; charset=UTF-8″%>
<%@ page pageEncoding=”UTF-8″ %>
2.在struts.properties中添加或在struts.xml文件中添加
struts.properties
struts.devMode=false
struts.enable.DynamicMethodInvocation=true
struts.i18n.reload=true
struts.ui.theme=simple
struts.locale=zh_CN
struts.i18n.encoding=UTF-8
struts.serve.static.browserCache=false
struts.url.includeParams=none
struts.xml
<constant name="struts.action.extension" value="do" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.custom.i18n.resources" value="messageResource"/>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="UTF-8" />
3、在web.xml文件中增加过滤器(注意过滤器的顺序)
<filter>
<filter-name>encodingFilter</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>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>跟上述方法,类似还有在action中设定字符编符.
HttpServletResponse response = null;
response = ServletActionContext.getResponse();
request.setCharacterEncoding(”utf-8″);
response.setContentType(”text/html;charset=utf-8″);通过上述方法,基本就可以搞定中文乱码的问题了。当然,也有例外(如web server的版本\数据库的版本等等)。象在我的一个项目碰到一个中文乱码,tomcate5.5是会乱码的,而在tomcate6中就不会。这边就涉 及到tomcate connector字符的设置了。
<Connector port=”80″ maxHttpHeaderSize=”8192″
maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
enableLookups=”false” redirectPort=”8443″ acceptCount=”100″
connectionTimeout=”20000″ disableUploadTimeout=”true” URIEncoding=”GBK” />
这个方法是下下策了,只有在前面的方法都无效时才使用。在action中直接使用request.getParameter()时;还是出现乱码。原因分析如下:
1、getParameter()是有带字符参数的。例:
String s = (String)request.getParameter(”txt”).getBytes(”iso-8859-1“);
2、String也可以带有字符参数。
String(byte[] bytes, String charsetName)
构造一个新的 String,方法是使用指定的字符集解码指定的字节数组。例:String s = new String(”中文”,”utf-8″);
3、综合上述两点,编写一个类来完成此项任务
public class ConvertCharacter{
public String Convert(String s){
String result;
byte[] temp ;
try{
temp = s.getBytes(”iso-8859-1″);
result = new String(temp,”utf-8″);
}
return result;
}
}
浙公网安备 33010602011771号