Chris K
Chris K

Reputation: 12341

Advise in AspectJ to change control flow

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?

Upvotes: 1

Views: 1069

Answers (2)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

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.

Upvotes: 4

Andrey Adamovich
Andrey Adamovich

Reputation: 20663

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.

Upvotes: 3

Related Questions