tags:

views:

168

answers:

2

I'm just starting to learn AspectJ, and I have use-case for say, User login. If a user's session data (cookies) doesn't match the stored data on the server, I want to change the function called. Say I have two operations:

class HttpServlet { 
   public function() { 
   } 
   public function2() { 
   }
   public doLogin() { 
   }
}

and I have advise such as:

public aspect UserLoggedIn {

    pointcut GreetingServer(): within(HttpServlet);
    pointcut requireAuth(): 
       GreetingServer() && execution(* function*(..));
    before(): requireAuth() {
        if ( notLoggedIn ) { 
          redirectToDoLoginAndAbortCalledFunction();
        }
    }
}

So how do I make redirectToDoLoginAndAbortCalledFunction() work?

+2  A: 

In our project we used servlet Filter for exact the same authentication purpose. Is there any reason you want to use AOP for that?

But in case you still need to use AspectJ for that, you should use around aspect in order to be able to interfer method call. We used similar technic for caching of method return values.

You can look at this article for an example http://www.theserverside.com/tt/blogs/showblog.tss?id=AspectJCaching.

Superfilin
No particular reason why. I'm trying to learn AspectJ and so trying to do things I'd normally do in other ways.
Chris Kaminski
+2  A: 

You will want to use around advice instead of before advice, something like below. Here is an example that assumes that both methods return boolean:

 boolean around(): requireAuth() {
    if ( notLoggedIn ) {           
        return redirectToDoLoginAndAbortCalledFunction();        
    } else {
        return proceed();
    }    
 }

You may also need to pass in parameters to your advice, which you can do by capturing the proper values in the pointcut using the this(), target(), and args() pointcuts.

Andrew Eisenberg
...this possibility to pick up additional context data as parameters (in a typesafe manner, wich compiler check) is the main strength of the aop-based solution. You couldn't do that with a servlet filter or an dynamic proxy
Ichthyo