一、新建一个Filter,代码如下:
package com.suzhou.util;
import java.io.IOException;
import javax.servlet.*;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;// ///要制定的编码,在web.xml中配置
protected FilterConfig filterConfig = null;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
String encoding = getEncoding();// //得到指定的编码名字
if (encoding != null)
request.setCharacterEncoding(encoding);// //设置request的编码
}
chain.doFilter(request, response);// /有机会执行下一个filter
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");// /得到在web.xml中配置的编码
}
protected String getEncoding() {
return (this.encoding);// /得到指定的编码
}
}
二、修改web.xml,添加:
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>com.suzhou.util.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、进入http://localhost:port/admin,选择Tomcat server/Service/Connector(port),把URI Encoding改成UTF-8,Use Body Encoding For URI Query Parameters:设置为true,点保存然后重新启动Tomcat即可。
记住,每个jsp页面的编码都为:
<%@ page contentType="text/html; charset=GBK" language="java" import="java.sql.*" errorPage="" %>
这样子不但能彻底解决中文参数问题(如http://menglikn:4000/suzhou/getMap.do?ditu=市区图),而且还能解决中文URL问题(如http://menglikun:4000/suzhou/空白页.html)