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
分享到:
相关推荐
本文将深入探讨如何使用Spring的IOC和DI特性,结合动态代理(Dynamic Proxy)来实现一种类似AOP(面向切面编程)的功能,以达到在不修改原有代码的情况下增强或拦截方法调用的目的。 **一、Spring IOC(控制反转)*...
在java编程使用CGLIB做动态代理时需要CGLIB依赖包支持,没有这个支持包,当导入import net.sf.cglib.proxy.Enhancer;或者import net.sf.cglib.proxy.MethodProxy;类似包时会提示错误,所以分享出来同大家共勉。
Cglib是Eclipse的Dynamic Proxies的一个补充,它在某些情况下提供了更高的性能。 Cglib的核心是基于ASM库,ASM是一个字节码操作和分析框架,可以直接生成和修改Java类和属性。ASM-commons和ASM-tree分别是ASM的辅助...
System.out.println("Doing something in the target class"); } } class MyMethodInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args,...
总的来说,JDK的Proxy适用于实现了接口的目标对象,而CGLIB则适用于未实现接口的对象。两者都可以帮助我们在不修改原有代码的情况下,通过代理对象在调用方法前后插入额外的逻辑,实现AOP的功能。在Spring框架中,这...
### Spring Cglib 中文说明 #### CGLIB 包简介与原理 CGLIB(Code Generation Library)是一个强大且高性能的代码生成库。它在众多面向切面编程(AOP)框架中扮演着核心角色,例如Spring AOP、Dynaop等。此外,它...
Service dynamicProxy = (Service) Proxy.newProxyInstance( Service.class.getClassLoader(), new Class[]{Service.class}, new MyInvocationHandler(new ServiceImpl())); dynamicProxy.doSomething(); ``` ...
- JDK Proxy基于接口实现,而CGLIB基于继承,因此CGLIB可以代理没有接口的类。 - JDK Proxy性能相对较慢,因为涉及到反射,而CGLIB通过字节码生成,性能更好。 - JDK Proxy易于理解和使用,CGLIB则需要更深入的...
Cglib是一个强大的高性能的代码生成库,它在Java运行时可以动态地生成子类,扩展已有对象的功能,而无需实现接口或继承原有类。在Java中,动态代理主要有两种方式:一是通过Java的反射API实现,二是通过第三方库如...
Spring支持两种主要的动态代理方式:Java Proxy和cglib。这两种方法都可以用来增强或拦截目标对象的方法调用,实现如AOP(面向切面编程)的功能。 首先,我们来看Java Proxy。Java Proxy是Java内置的动态代理机制,...
**CGLib库详解** CGLib,全称Code Generation Library,是一个强大的高性能的代码生成库,它在Java世界中被广泛使用,特别是在动态代理和AOP(面向切面编程)领域。这个库允许开发者在运行时动态创建类或者增强已有...
使用CGLib库需要导入的Jar包,官网下载,亲测可用! cglib - Byte Code Generation Library ... It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.
2. **无需接口**:CGLib可以对没有实现接口的类进行代理,这是Java动态代理(JDK Proxy)无法做到的。 3. **广泛支持**:许多知名框架如Spring AOP、Hibernate等都使用了CGLib作为底层的动态代理技术。 ### 应用...
CGLIB,全称为Code Generation Library,是一个强大的高性能的代码生成库,被广泛应用于Java世界,尤其是Spring框架中。它允许程序在运行时动态地创建Java对象并扩展已有类的功能。CGLIB是通过字节码技术实现的,而...
CGLIB介绍与原理(部分节选自网络) 一、什么是CGLIB? CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。通常可以使用Java的动态代理创建代理,但当要...
Cglib子类代理是Java动态代理的一种实现方式,它主要通过字节码技术在运行时动态创建一个目标对象的子类,以此来实现代理功能。Cglib是一个强大的高性能的代码生成库,它在许多AOP(面向切面编程)框架中被广泛应用...
CGLIB,全称为Code Generation Library,是一个强大的高性能的代码生成库,它在Java世界里被广泛应用,尤其是在Spring框架中。CGLIB是基于ASM(一个底层的Java字节码操作和分析框架)来实现的,它允许开发者在运行时...
- 动态代理:当JDK的Proxy不能满足需求时,比如目标类没有实现接口,CGLIB可以提供解决方案。 - 缓存机制:比如在ORM框架Hibernate中,CGLIB用于缓存对象,提高查询效率。 下面是一个简单的CGLIB使用示例: ```...