利用Filter实现全局编码(装饰者模式和动态代理模式)
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.security.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>
/**
*编码过滤器;
*/
public class EncodingFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
HttpServletRequest req=(HttpServletRequest) request;
EnhanceRequest enhanceRequest=new EnhanceRequest(req);
chain.doFilter(enhanceRequest,response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
/**
* 加强版的HttpServletRequest;
*/
private class EnhanceRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public EnhanceRequest(HttpServletRequest request) {
super(request);
this.request=request;
}
/**
* 重写HttpServeltRequest的getParameter()方法;
* 作用:将编码格式转化为UTF-8;
*/
@Override
public String getParameter(String name) {
String parameter=request.getParameter(name);
try {
parameter=new String(parameter.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parameter;
}
}
}
/**
*编码过滤器;
*/
public class EncodingFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
/**
* 代理对象;
* 将ServletRequest转化为HttpServletRequest;
*/
final HttpServletRequest req=(HttpServletRequest) request;
/**
* 动态代理;
* 动态创建代理对象;
*/
HttpServletRequest enhanceRequest=(HttpServletRequest)Proxy.newProxyInstance(
req.getClass().getClassLoader(),
req.getClass().getClasses(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName=method.getName();
if(methodName.equals("getParameter")){
String result=(String) method.invoke(req,args);
result=new String(result.getBytes("ISO-8859-1"),"UTF-8");
return result;
}
return method.invoke(req, args);
}
});
chain.doFilter(enhanceRequest,response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}