The compare of Filter,CGLib and Dynamic proxy

1.If you want to use Filter for intercept ,you shoule implements Filter interface which have three methods you must implement it:init(),doFilter() and destroy() :

public class FilterTest implements Filter{

	private ServletContext context;
	
	//init the ServletContext
	public void init(FilterConfig arg0) throws ServletException{
		String name = arg0.getInitParameter("name");
		System.out.println("My name is "+name);
		context = arg0.getServletContext();
	}
	
	public void doFilter(ServletRequest arg0,ServletResponse arg1,FilterChain arg2) throws IOException,ServletException{
		System.out.println("Username="+arg0.getParameter("username"));
		String name = (String)arg0.getParameter("username");
		if(name!=null&&name.equals("monster"))
		{
			PrintWriter pt = arg1.getWriter();
			pt.print("sorry,you are a monster");
			return;
		}
		context.log("["+arg0.getRemoteHost()+"] request" + ((HttpServletRequest)arg0).getRequestURI());
		arg2.doFilter(arg0, arg1);
		context.log("["+arg0.getRemoteHost()+"] done");
	}
	//clean up
	public void destroy(){
		context = null;
	}
}

 and in order to trigger this Filter ,you shoule set the relationship with the action you want to filter:

	<filter>
	<filter-name>FilterTest</filter-name>
	<filter-class>mysrc.FilterTest</filter-class>
	<init-param>
	<param-name>name</param-name>
	<param-value>tom</param-value>
	</init-param>
	</filter>
	<filter-mapping>
	   <filter-name>FilterTest</filter-name>
	   <url-pattern>/login</url-pattern>
	</filter-mapping>

	<servlet>
	  <servlet-name>LoginAction</servlet-name>
	  <servlet-class>mysrc.LoginAction</servlet-class>
	</servlet>
	<servlet-mapping>
	  <servlet-name>LoginAction</servlet-name>
	  <url-pattern>/login</url-pattern>
	</servlet-mapping>

 the value in the <init-param> can be get this method FilterConfig.getInitParameter("name");If the usrname you inputted is "monster",this is will be blocked by the Filter.see the detailed before the doFilter() method.

2.DynamicProxy implements the InvocationHandler(note: this proxy just work for interface,if not,obj.getClass().getInterfaces() will return no value,pls refer to CGLib for handling):

public class DynamicProxy implements InvocationHandler{
	
	Object target;
	
	public Object init (Object obj){
		this.target = obj ;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		Object result = null ; 
		try {
			if(method.getName().startsWith("save")){
				System.out.println("Before save by Proxy");
				result = method.invoke(target, args);
				System.out.println("After save by Proxy");
			}
			
			if(method.getName().startsWith("load")){
				System.out.println("Before load by Proxy");
				result = method.invoke(target, args);
				System.out.println("After load by Proxy");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		return result;
	}

}

 init(): get the instance of proxy method.

 Test method with proxyFactory.

public class DynamicProxyFactory {

	public static Object getClassInstance(String cn){
		Object result = null;
		try {
			result = Class.forName(cn).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static Object getProxyInstance(String cn){
		Object result = null;
		
		DynamicProxy dyProxy = new DynamicProxy();
		
		try {
			result = dyProxy.init(Class.forName(cn).newInstance());
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return result;
	}
	
	public static void main(String args[]) throws Throwable{
		
		Object proxy = DynamicProxyFactory.getProxyInstance("ProxyTest.TestImp");

  		TestInterface test = (TestInterface)proxy;
  		test.load();
  		}
}

 output:

    Before load by Proxy
    Load() Method of TestImp
    After load by Proxy

 

3.if the object isnot the interface, you shoule use cglib instead of dynamic proxy:

At first,create a proxy implements MethodInterceptor():

public class AuthorProxy implements MethodInterceptor{

	private String name ; 
	public AuthorProxy(String name){
		this.name = name;
	}
	
	public Object intercept(Object arg0, Method arg1, Object[] arg2,
			MethodProxy arg3) throws Throwable {
		// TODO Auto-generated method stub
		if(!"admin".equals(name))
		{
			System.out.println("Sorry,you donot have the privilege to access, please contact the adminstrator!");
			return null;
		}else{		
		return arg3.invokeSuper(arg0, arg2);
		}
	}

}

 

then create a factory to get the instance of proxy:

public class OperationDAOFactory {

	private static OperationDAO operDao = new OperationDAO();
	
	public static OperationDAO getOperationDAO(){
		return operDao;
	}
	
	public static OperationDAO getAuthorInstance(AuthorProxy authorProxy){
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(OperationDAO.class);
		enhancer.setCallback(authorProxy);
		enhancer.setCallbackFilter(new AuthorProxyFilter());
		
		return (OperationDAO)enhancer.create();
	}
}

 test method:

  public  static void doOperation(OperationDAO dao){
		dao.create();
		dao.save();
	}
    
  public static void main(String args[]){
    		
    	OperationDAO operOfAdmin = OperationDAOFactory.getAuthorInstance(new AuthorProxy("admin"));
    	doOperation(operOfAdmin);
    	
    	OperationDAO operOfMonster = OperationDAOFactory.getAuthorInstance(new AuthorProxy("monster"));
    	doOperation(operOfMonster);
    }

 ok,from these methods.we know that : our method are including these proxy implements method.just do some handling with before trigger our mehtod or after.

  if any opinions, pls share it ,thx

你可能感兴趣的:(DAO,servlet,Access,UP)