(转载)http://www.iteye.com/topic/31023
软件环境 : Eclipse3.1.1 , AJDT 1.3 , JDK1.4.2 , AspectJ1.5, Struts1.1 , Jetty5.1.6
场景介绍 : workspace中已存在一个java项目,并已部署与Jetty服务器上,这里我采用了一个简单的struts项目,我将演示如何在不改变原有项目的任何代码和配置的基础上,在runtime对struts项目中的一些代码进行拦截。
首先,让我们来新建已个AspectJ项目,名字为AspectJDemo。
在新建project的build path中加入aspectjrt.jar
在Aspectj InPath中加入aspectj代码中需要用到的类及jar,这边我加入了struts的所有jar及StrutsDemo的类编译路径
好,接下来说一下我要拦截的代码片断,在原项目中有一个名叫UserLoginForm的FormBean,希望在runtime的时候,当struts调用这个form中的setUsername方法时拦截代码,相关的struts代码如下:
public class UserLoginForm extends ActionForm { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
public class UserLoginAction extends Action { private final String LOGIN_FAILURE = "failure"; private final String LOGIN_SUCCESS = "success"; public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception { UserLoginForm ulf = (UserLoginForm)form; LOG.info("Username:"+ulf.getUsername()+"+Password:"+ulf.getPassword()); return mapping.findForward(LOGIN_FAILURE); } }
<html:form action="/login" focus="username" onsubmit=""> <table border="0" width="100%"> <tr> <th align="right">Username:</th> <td align="left"> <html:text property="username" size="16" maxlength="18" /> </td> </tr> <tr> <th align="right">Password:</th> <td align="left"> <html:password property="password" size="16" maxlength="18" redisplay="false" /> </td> </tr> <tr> <td align="right"><html:submit value="Submit" /></td> <td align="left"><html:reset /></td> </tr> </table> </html:form>
public aspect LoginAspect { //建立一个pointcut,这个pointcut对所有方法签名为 //public void setUsername(String) 的方法被执行的时候有效 public pointcut setUsername() : execution (public void setUsername(String)); //设定拦截位置,在setUsername这个pointcut执行前打印出一段message before() : setUsername() { System.out.println("setUsername method has been invoked!!!"); } }
<Call name="addWebApplications"> <Arg></Arg> <Arg>./webapp/</Arg> <Arg><SystemProperty name="jetty.home" default="."/>/etc/webdefault.xml</Arg> <Arg type="boolean">true</Arg><!--extract WARs--> <Arg type="boolean">false</Arg><!-- java 2 compliante class loader --> </Call>
<?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="lenson.presentation.LoginAspect"/> </aspects> </aspectj>
-Djetty.home="D:\development\jetty-5.1.6"
./jetty5.xml