java中的代理

对指定的接口或类的某一个方法进行功能扩展,可以使用代理。

使用示例:

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        //需求:要对request的getParameter方法进行功能扩展,处理get提交中文编码问题
        //对request创建代理对象
            HttpServletRequest proxy =(HttpServletRequest)Proxy.newProxyInstance(
            request.getClass().getClassLoader(),//指定当前使用的类加载器
            new Class[] {HttpServletRequest.class},//目标对象实现的接口类型
            new InvocationHandler(){  //事件处理器
            public Object invoke(Object proxy,Method method,Object[] args)throws Throwable
               {
                 //定义方法返回值
                 Object returnValue = null;
                 //获取方法名
                 String methodName = method.getName();
                 //判断 扩展方法的方法名
                 if("getParameter".equals(methodName))
                 {
                   //方法的参数封装在args中
                   String value = request.getParameter(args[0].toString());//获取请求的值
                   //获取提交方式
                   String submitMethod = request.getMethod();
                   //如果是get提交,需要对数据进行处理
                   if("GET".equals(submitMethod))
                   {
                      value = new String(value.getBytes(),"UTF-8");   
                   }
                   return value;
                 }
                 else
                 {
                   //执行request对象的其他方法
                   returnValue = method.invoke(request,args);
                 }
                 return returnValue;
               }
           }
       )

        chain.doFilter(proxy, response);
    }

猜你喜欢

转载自blog.csdn.net/smile_po/article/details/78551261