packagecn.itcast.goods.filter;importjava.io.IOException;importjava.io.UnsupportedEncodingException;importjava.util.Map;importjava.util.Map.Entry;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletRequestWrapper;importjavax.servlet.http.HttpServletResponse;/*** 处理整个web应用全站乱码
* 1)处理请求参数乱码
* 2)处理响应正文乱码
*@authorRoySun
**/
public class MixCodeFilter implementsFilter{
@Overridepublic voiddestroy() {}
@Overridepublic voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;//针对post提交方式,这一句即可处理接收请求中的乱码
request.setCharacterEncoding("utf-8");/**过滤器中处理响应正文乱码,
*所有拦截到的资源的乱码问题都可以解决*/response.setContentType("text/html;charset=utf-8");/** 采用装饰者模式,将request对象进行包装,
* 在装饰类中重写getParameter等获取参数的方法*/MyHttpServletRequest myRequest= newMyHttpServletRequest(req);
chain.doFilter(request, res);
}
@Overridepublic void init(FilterConfig onfig) throwsServletException {}
}//装饰类,对HttpServletRequest类进行装饰,重写获取请求参数的方法
class MyHttpServletRequest extendsHttpServletRequestWrapper{privateHttpServletRequest request;//构造方法
publicMyHttpServletRequest(HttpServletRequest request) {super(request);this.request =request;
}
@OverridepublicString getParameter(String name) {return this.getParameterValues(name)==null? null:this.getParameterValues(name)[0];
}
@OverridepublicString[] getParameterValues(String name) {return this.getParameterMap().get(name);
}private boolean isEncode=true;
@Overridepublic MapgetParameterMap() {if("GET".equalsIgnoreCase(request.getMethod())){//针对get提交方式进行手动编解码
Map map =request.getParameterMap();if(isEncode){for (Entryentry : map.entrySet()) {
String[] params=entry.getValue();for(int i=0;i
System.out.println("过滤器之前的参数:" +params[i]);
params[i]=new String(params[i].getBytes("iso8859-1"), "utf-8");
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
isEncode= false;
}returnmap;
}else{//其余6种提交方式
returnrequest.getParameterMap();
}
}
}