标签:
1、利用filter和动态代理解决全站乱码问题
1.1filter的代码
package com.baowei.filter; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; 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.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CharctorFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("utf-8"); chain.doFilter(new MyRequest(request).getProxyRequset(), response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } class MyRequest implements InvocationHandler { private HttpServletRequest request; public MyRequest(HttpServletRequest request) { this.request = request; } // 返回增强后的代理对象 public HttpServletRequest getProxyRequset() { return (HttpServletRequest) Proxy.newProxyInstance(request .getClass().getClassLoader(), request.getClass() .getInterfaces(), this); } // 对真实request对象的getparameter进行增强 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!method.getName().equals("getParameter")) { return method.invoke(request, args); } if (!((HttpServletRequest) request).getMethod().equalsIgnoreCase( "get")) { return method.invoke(request, args); } String value = (String) method.invoke(request, args); if (value == null) { return null; } return new String(value.getBytes("iso8859-1"), "UTF-8"); } } }
1.2 filter的配置
<filter> <filter-name>CharctorFilter</filter-name> <filter-class>com.baowei.filter.CharctorFilter</filter-class> </filter> <filter-mapping> <filter-name>CharctorFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
标签:
原文地址:http://www.cnblogs.com/zhangbaowei/p/4874636.html