Search code examples
javaplayframeworkplayframework-1.x

Using a separate Controller for Interception


I have created a Controller named InterceptionLogger.java which will contain only the Interception methods. The other Controller namely Application will contain all the action methods and use the Interception using the @With annotation.

This is the Application.java Controller:

@With(InterceptionLogger.class)
public class Application extends Controller {

public static void index() {
    System.out.println("Inside index!!!");
    render();
}

public static void welcome(String txtName){     
    render(txtName);
}

If the InterceptionLogger.java Controller is this:

public class InterceptionLogger extends Controller {   

@Before
static void logBefore(){
    System.out.println("Inside \"logBefore\" method of App Controller");
}

@After
static void logAfter(){
    System.out.println("Inside \"logAfter\" method of App Controller");
}

}

When I run the Application, the Output is:

Inside "logBefore" method of App Controller
Inside index!!!
Inside "logAfter" method of App Controller

Fine, as expected.

But If I change the InterceptionLogger.java to this:

public class InterceptionLogger extends Controller {   

@Before(only="welcome")
static void logBefore(){
    System.out.println("Inside \"logBefore\" method of App Controller");
}

@After(only="index")
static void logAfter(){
    System.out.println("Inside \"logAfter\" method of App Controller");
}

}

Then I am getting this output for index :

Inside index!!!

In this case, why is the statement Inside "logAfter" method of App Controller not getting printed in the console?

How to make it work?


Solution

  • Play! is looking for the intercepted methods in the current controller. You need to supply the full path, if the method is in another controller:

    @Before(only="Application.welcome")
    static void logBefore(){
        System.out.println("Inside \"logBefore\" method of App Controller");
    }
    
    @After(only="Application.index")
    static void logAfter(){
        System.out.println("Inside \"logAfter\" method of App Controller");
    }