您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
动态代理和静态代理的区别
动态代理是在运行时,将代理类加载到内存中
静态代理是提前把代理类写好,然后再启动项目的时候把代理类加载到内存中
动态代理
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 强转
final HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1 post乱码
request.setCharacterEncoding("UTF-8");
//2 使用动态代理增强request
HttpServletRequest proxyRequest = (HttpServletRequest)Proxy.newProxyInstance(
EncodingFilter.class.getClassLoader(),
new Class[] { HttpServletRequest.class } ,
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//增强
String methodName = method.getName();
if("getParameter".equals(methodName)){
//args 所有参数 --> getParameter("username");
//1 从tomcat request获得原始数据(乱码)
String value = request.getParameter((String)args[0]);
//2 如果get请求处理乱码
if("GET".equals(request.getMethod())){
value = new String( value.getBytes("ISO-8859-1") , "UTF-8");
}
//3 将结果返回
return value;
}
//不需要增强的直接执行目标类的方法
return method.invoke(request, args);
}
});
chain.doFilter(proxyRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
静态代理(装饰者模式)
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1 post乱码
request.setCharacterEncoding("UTF-8");
//2 使用装饰者增强request
MyRequest myRequest = new MyRequest(request);
chain.doFilter(myRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
/**
增强response对象,提供使用装饰者设计模式编写默认类:HttpServletResponseWrapper
*/
public class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request; //tomcat request
public MyRequest(HttpServletRequest request){
super(request);
this.request = request;
}
//增强
@Override
public String getParameter(String name) {
//1 直接从tomcat的request获得数据
String value = this.request.getParameter(name);
//2 如果是get,处理
// * 请求方式
String method = this.request.getMethod();
if("GET".equals(method)){
try {
value = new String( value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return value;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。