1、web.xml中的配置代码:
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>cn.conris.util.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>gbk</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
2、Filter中的过滤代码:
package cn.conris.util; 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; /** * 采用Filter统一处理字符集 * * @author xuchao * */ public class EncodingFilter implements Filter { private String encoding = "GBK"; @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 设置web.xml中配置的字符集 if (encoding != null) { // 设置request字符编码 request.setCharacterEncoding(encoding); // 设置response字符编码 response.setContentType("text/html;charset=" + encoding); } // 继续执行 chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { String encoding = filterConfig.getInitParameter("encoding"); if (encoding != null && encoding.trim().length() > 0) { this.encoding = encoding; } } }
PS:Filter的方式只适合于post的提交方式,对于get的提交方式不起作用,而且get提交存在一定的安全问题,所以建议大家还是用post方式提交数据比较好一些。