package com.demo.test;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 characterEncodingFilter implements Filter { private String characterEncoding; private boolean enabled; public void destroy() { // TODO Auto-generated method stub characterEncoding = null;//销毁时清空资源 } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub if(enabled || characterEncoding != null){ //如果启用该Filter request.setCharacterEncoding(characterEncoding);//设置reques编码 response.setCharacterEncoding(characterEncoding);//设置response编码 } chain.doFilter(request,response );//doFilter,执行下一个Filter或者Servlet } public void init(FilterConfig config) throws ServletException { //初始化时加载参数 // TODO Auto-generated method stub characterEncoding = config.getInitParameter(characterEncoding);//编码方式 enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());//启用 } }
characterEncoding表示编码方式,enabled表示是否启用编码,分别从初始化参数中取值。
web.xml中的配置如下:
index.jsp characterEncodingFilter com.helloweenvsfei.filter.CharacterEncodingFilter characterEncoding UTF-8 enabled true characterEncodingFilter /*
如果使用的字符编码Filter、request中取出的字符可能是乱码,否则不会出乱码。页面编码的方式与Filter编码方式必须一致。另外,如果表单是GET方式提交的,还需要修改Tomcat的conf/servlet.xml配置文件,制定URIEncoding(默认为IOS-8859-1);否则,依然会出现乱码。修改如下:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8">