Those who have used the Filter interface or Interceptor concept on any other framework will find some similar functionality in VRaptor's interceptors.
The idea is that an interceptor allows you to run some code before any bussiness logic and after the view process has finished.
package org.vraptor.example.interceptor; public class SimpleInterceptor implements Interceptor { private static volatile int hitCount = 0; private static volatile int concurrentHits = 0; public void intercept(LogicFlow flow) throws LogicException, ViewException { // before logic hitCount++; concurrentHits++; System.out.printf("This is the hit number %d%n", hitCount); // executes logic and redirects to view flow.execute(); // after view rendering concurrentHits--; System.out.println("After view..."); } }
package org.vraptor.example.interceptor; @Component("simple") @InterceptedBy(SimpleInterceptor.class) public class InterceptedTest { public void test() { try { System.out.println("Going to sleep"); Thread.sleep(10000); } catch(InterruptedException ex) { ex.printStackTrace(); } } }
simple/test.ok.jsp
<html> <% System.out.println("Hello scriplet!"); // note: do not use scriplet in a real life application! %> Done... </html>
This is the hit number 1 Going to sleep Hello scriplet! After view...
So note that the first line is the interceptors execution before calling flow.execute. Then your component and logic execution is done (second line).
The redirection occurs (line 3) and the rest of your intercept method is executed (last line).
So you get the following flow:
Instantiate Interceptor --> Call intercept method --> Instantiate Bussiness Component --> Read parameters --> Call Logic method --> Redirect to view --> Finished the intercept method
You can use the @InterceptedBy tag to supply multiple Interceptors:
@InterceptedBy( { Interceptor1.class, Interceptor2.class } )
If you have a big list of interceptors which is common to a lot of classes, you can extends InterceptorStack for a easier use:
public static class CommonInterceptors extends InterceptorStack { public Stack() { super(DaoInterceptor.class, UserLoginInterceptor.class); } }
Than, instead of:
@InterceptedBy( { DaoInterceptor.class, UserLoginInterceptor.class } )
You would have:
@InterceptedBy( { CommonInterceptors.class } )