package xxx; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class SetCharacterEncodingFilter implements Filter{ String encoding = null; FilterConfig filterConfig = null; /** 初始化方法 */ public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); } /** 过滤处理方法 */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding!=null){ //对请求进行编码设置 request.setCharacterEncoding(encoding); HttpServletRequest httprequest=(HttpServletRequest) request; if(httprequest.getMethod().equalsIgnoreCase("get")){ MyRequest myRequest = new MyRequest(httprequest); myRequest.setEncoding(encoding); chain.doFilter(myRequest, response); }else{ //将处理权转交给下一个处理器 chain.doFilter(request,response); } }else{ //将处理权转交给下一个处理器 chain.doFilter(request,response); } } /** * Wrapper包装类,装饰设计模式,内部有个真实对象的引用 */ class MyRequest extends HttpServletRequestWrapper{ private HttpServletRequest request; private String encoding; public MyRequest(HttpServletRequest request) { super(request); this.request = request; } public void setEncoding(String encoding) { this.encoding = encoding; } @Override //重写父类的方法 public String getParameter(String name) { String[] p = getParameterMap().get(name); if(p!=null&&p.length>0){ return p[0]; }else{ return null; } } @Override //获取参数的方法 public Map<String, String[]> getParameterMap() { //获取客户端传过来的参数数据,并且包装成一个Map集合 Map<String, String[]> resMap = new HashMap<String, String[]>(); Map map = request.getParameterMap(); Set set = map.keySet(); Iterator it = set.iterator(); while(it.hasNext()){ String key=(String) it.next(); Object value= map.get(key); if(value instanceof String[]){ String[] values=(String[]) value; for(int i=0;i<values.length;i++){ try { values[i] = java.net.URLDecoder.decode(values[i], encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //翻页参数中的中文解码,编码在dbpage.java中进行的 } resMap.put(key, values); } } return resMap; } } /** 销毁方法 */ public void destroy() { this.encoding = null; this.filterConfig = null; }}