不多说了,直接上代码了,比较容易理解,主要是get乱码问题
//将ServletRequest强转为HttpServletRequest
final HttpServletRequest hsr=(HttpServletRequest)request;
//post转码
request.setCharacterEncoding("utf-8");
//get转码---动态代理方法
//2、创建代理对象【固定】
//参数一:被代理对象的类加载器。 实现方式:被代理对象.getClass().getClassLoader()
//参数二:被代理对象的接口数组。 实现方式:被代理对象.getClass().getInterfaces()
//参数三:处理类【用来增强方法的】
//增强代码需要写在处理类的 invoke方法中即可
HttpServletRequest obj = (HttpServletRequest)Proxy.newProxyInstance(
hsr.getClass().getClassLoader(), //获取被代理类类加载器
hsr.getClass().getInterfaces(), //获取被代理类实现类的接口
new InvocationHandler() {
//参数一: Object proxy 代理对象。没用
//参数二: Method method 被代理对象的对应方法
//参数三: Object[] args 被代理对象对应方法执行时,传递的实参
@Override
public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
// TODO Auto-generated method stub
//针对getParameter方法进行增强
if("getParameter".equals(method.getName())){
//获取提交方式
String m = hsr.getMethod();
if("GET".equalsIgnoreCase(m)){
//调用原来的方法
String invoke = (String) method.invoke(hsr, arg2);
String re=null;
try {
//转码
re=new String(invoke.getBytes("iso8859-1"),"utf-8");
} catch (Exception e) {
}
return re;
}
}
return method.invoke(hsr, arg2);
}
});
chain.doFilter(obj, response);