整体思想,编码方法统一(utf-8)
一:页面显示中文乱码问题:
解决:<%@ page language="java" pageEncoding="UTF-8" %>
二:传递参数中文乱码问题:
解决:1. 在tomcat中修改server.xml文件。
在本机上 D:\Tomcat5.5\conf目录下找到server.xml文件,在文件的<Connector>标签中加上红色部分
<Connector port="8888" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>
第一步主要是为了防止在get请求时传递参数为中文如:http://localhost:8888/login?username=小王
2. 编写过滤器(Filter);
<1>先编写CharactorEncodingFilter.java类,这个类要实现 servlet 的 Filter 接口
具体内容如下:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharactorEncodingFilter implements Filter {
private String encoding = "ISO8859-1";
private FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
String code = config.getInitParameter("encoding");
if (code != null) {
encoding = code;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void destroy() {
config = null;
}
}
<2> 要在web.xml文件中,配置filter
具体内容如下:
<filter>
<filter-name>charactorEncodingFilter</filter-name>
<filter-class>
com.oakpip.struts.filter.CharactorEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charactorEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三:国际化中文乱码问题:
解决:用JDK的native2ascii工具对资源文件进行转换