Clean Cache Struts2 Interceptor Tutorial

Source: Internet
Author: User

Page 1 of 2

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


This is very common, developer wants to restrict the browser to cache rendered pages. And the the-the-the-used to achieve are having code similar to the following mostly in the JSP pages to prevent caching. Either we have this code in all the JSPs pages or more friendly A-common JSP page where we have this code an D include it in all the main JSP pages. If we are using a 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 has a JSP page to does this. This is the we keep the code clean in JSP pages.

A little bit about interceptor before we start coding, interceptors is 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 is isn't thread safe, since it is a shared among all the action execution context;

Writing The Interceptor:
Now, 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 from writing an interceptor are to extend Abstractinterceptor class which have an abstract me Thod 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 中文版 it means that if INVOCATION.INVOKDE () call isn't there then the next interceptor lined up would not execu Te.
    3. The String return of the method is also very important, as this would help identify which result is returned
      From the action. This is could also are a place to modify the result value ("Success", "error" etc) if required and a lot of interceptor do. If not sure and always return the value coming from Invocation.invokde ().

After these steps in consideration here's how the Intercept method looks like.

Public String intercept (actioninvocation invocation) throws Exception {        String result=invocation.invoke ();        return result;}

  

Page 2 of 2

Now coming back to our clear cache implementation, we need to execute the SetHeader () method on response object, but

We need to the response object. But how?

The answer is in the method signature:

Public String intercept (actioninvocation invocation)

  

To get response object we'll make use of invocation object reference. Here's how.

Actioncontext Ctx=invocation.getinvocationcontext ();

  

Actioncontext is the context in which the actions execute. So it had encapsulated many behavior and properties that represents the action execution context.

Actioncontext context= (Actioncontext) invocation.getinvocationcontext (); HttpServletResponse response= (HttpServletResponse) context.get (strutsstatics.http_response);

  

And we are doing, finally my class looks like this:

Package com.bullraider.apps.interceptors; Import javax. Servlet.http.httpservletresponse;import Org.apache.struts2.StrutsStatics; Import Com.opensymphony.xwork2.actioncontext;import Com.opensymphony.xwork2.actioninvocation;import Com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class Clearcacheinterceptor  extends abstractinterceptor{    @Override public    String Intercept ( Actioninvocation invocation) throws Exception {        actioncontext context= (actioncontext) Invocation.getinvocationcontext ();        HttpServletResponse response= (HttpServletResponse) context.get (strutsstatics.http_response);        Response.setheader ("Cache-control", "No-cache");        Response.setheader ("Pragma", "No-cache");        Response.setdateheader ("Expires", 0);        String Result=invocation.invoke ();        return result;}    }

  

One more important thing we skipped here are that 1st property of interceptor. When the interceptor are in pre processing state (before executing the next interceptor or action), it executes the lines of Code that comes before-the-Invocation.invoke () in the Intercept method. And in post processing state It execute the lines comes after the Invoke method.

In our code it seems meaningful if we should has the code after the Invocation.invoke () because the Respon SE is given-only in the post processing time. But If you try recollecting the Servlets request and response model, then it becomes clear this no matter where you keep t He we code (before or after the call to invoke ()). It does the same thing. So the 1st is interceptor doesn ' t apply to us in this situation.

Lets Now stitch we interceptor in Struts.xml.
 

<! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/dtds/ Struts-2.0.dtd "><struts>    <package name=" test "extends=" Struts-default ">        <interceptors >            <interceptor name= "Clear-cache"                class= "Com.bullraider.apps.interceptors.ClearCacheInterceptor"/ >        </interceptors>        <action name= "Test" class= "Com.bullraider.apps.actions.TestAction" >            <interceptor-ref name= "Clear-cache"/>            <result name= "Success" >/success.jsp</result>        </action>    </package></struts>

  

Lets has a look at the action element, there are an element <interceptor-ref> and name with value Clear-cache. What it means is; Apply this interceptor Clear-cache in this action named Test.

The "Clear-cache" is defined inside, the <interceptor> element with value "Clear-cache" and class as "Com.bullraider. Apps.interceptors.ClearCacheInterceptor ". And this declaration have to be kept inside the <interceptors> element. We'll have more than discussion in the 3rd tutorial later.

And for obvious reason I am not going to discuss about the action class Testaction as follows.

Package com.bullraider.apps.actions; public class Testaction {public    String execute () {        System.out.println ("Inside Action");        Return "Success";    }}

  

Download Cacheinterceptorexample.war and run in your container to test it. The well if you is wondering how would know if the headers applied in the response i.e success page. I use Firebug extension for Firefox.

Clean Cache Struts2 Interceptor Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.