The first tutorial concentrate on creating a basic interceptor, but useful in a typical web application.


This is very common that developer wants to restrict the browser to  cache rendered pages. And the way we used to achieve is having code similar to the following mostly in the JSP pages to prevent caching. Either we have this code in all the JSP pages or more friendly way is to have a common JSP page where we have this code and include it in all the main JSP pages.If we are using tiles or any such framework we follow the same strategy.

 

response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);


           

Struts2 helps us achieve this through interceptors and we don't want to have a JSP page to do this. This way we keep the code clean in JSP pages.

A little bit about interceptor before we start coding, interceptors are much like Servlet Filters as interceptors
follows the same design patters that a Servlet filter; intercepting filter.


Properties of Interceptors: 

  1. Interceptors executes twice per action execution. One before the action execute and after the action executes.
  2. The order in which interceptors execute matters a lot, and interceptors do  mean it. Though not all interceptors.
  3. Interceptors are not thread safe, since it is shared among all the action execution context ;so care should be taken.

Writing the interceptor:
Now that we know about the interceptors lets start.

package com.bullraider.apps.interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ClearCacheInterceptor  extends AbstractInterceptor{
   
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        return null;
    }
}

 

  1. The typical and most trivial way of writing an interceptor is to extend AbstractInterceptor class which has an abstract method that we  must override.
  2. The method intercept should execute invocation.invoke() in the intercept method. The reason is pretty similar to doFilter() method call of Servlet Filter inside doFilter() method. In plain English it means that if invocation.invokde() call is not there then the next interceptor lined up will not execute.
  3. The String return of the method is also very important, as this will help identify which result is returned
    from the action. This is could also be a place to modify the result value ( "success","error" etc) if required and a lot of interceptor do.If not sure then always return the value coming from invocation.invokde().

 After these steps in consideration here is how the intercept method looks like.
 

public String intercept(ActionInvocation invocation) throws Exception {
        String result=invocation.invoke();
        return result;
}