package com.itheima.c_proxy.encoding;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
// 1强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 创建代理对象
HttpServletRequest requestProxy = (HttpServletRequest) Proxy.newProxyInstance(
HttpServletRequest.class.getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("getParameter".equals(method.getName())) {
//获取请求方式
String m = request.getMethod();
if("get".equalsIgnoreCase(m)) {
String s = (String) method.invoke(request, args);//相当于resquest.getParameter(args);
return new String(s.getBytes("iso8859-1"),"utf-8");
}else if("post".equalsIgnoreCase(m)){
request.setCharacterEncoding("utf-8");
return method.invoke(request, args);
}
}
//不需要加强的方法
return method.invoke(request, args);
}
});
// 2放行
chain.doFilter(requestProxy, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
1. 使用Proxy类来生成代理对象的一些代码如下:
/**
* 使用JDK的方式生成代理对象
* @author Administrator
*/
public class MyProxyUtils {
public static UserDao getProxy(final UserDao dao) {
// 使用Proxy类生成代理对象
UserDao proxy = (UserDao) Proxy.newProxyInstance(dao.getClass().getClassLoader(),
dao.getClass().getInterfaces(), new InvocationHandler() {
// 代理对象方法一直线,invoke方法就会执行一次
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("save".equals(method.getName())){
System.out.println("记录日志...");
// 开启事务
}
// 提交事务
// 让dao类的save或者update方法正常的执行下去
return method.invoke(dao, args);
}
});
// 返回代理对象
return proxy;
}
}