Introduction to Interceptors in Struts 2

Interceptors are one of the Struts 2 components, others being ActionContext, the ValueStack and OGNL. Interceptors allow cross-cutting functionalities to be implemented before or after the actual action gets fired. Thus, provides for the pre-processing and post-processing logic on the action.

Note that, the action does not wait for the post-processing logic to finish.

ValueStack – Storage area holding all the associated data while processing the request, serves as the central data location rather than passing it around. Data in the valueStack persists through all the request processing through all phases, since it is stored in a ThreadLocal context called the ActionContext. Thus, valueStack is accessible from anywhere in the same thread of execution.


OGNL – Powerful expression language that is used to reference and manipulate properties on the valueStack. Can be used by both interceptors and results to target the values on the valueStack. It can efficiently bind the HTML form fields to the data objects on the valueStack for data transfer. It can also pull the data to all view types as well.

With the help of Interceptors we can:

  1. Provide some pre-processing logic
  2. Provide some post-processing logic
  3. Do Logging
  4. Data validation
  5. Type conversion
  6. File upload
  7. Exception Handling

Interceptors in Strut 2In the above figure, the FilterDispatcher has already done it’s controller task by selecting appropriate action to handle the request. ‘Invoke Action‘ is the point in the above figure where the flow starts.

Before reading this, I hope you might have gone through the previous article on CREATE YOUR FIRST LOGIN APPLICATION USING STRUTS, which would give you the prior idea about the flow and most importantly about the significance of struts.xml file.

The struts.xml file will remain the same here as well, except that we will be adding some interceptor entries to it as:

MyLoggingInterceptor.java

MyLoggingInterceptor is the custom Interceptor class that I want to add it above all other interceptors.

login.jsp

So, everytime ‘login‘ action is invoked, it will execute the set of interceptors within ‘loggingStack‘.
Everytime the login action returns ‘success‘, the application navigates to the corresponding URL mapping i.e. /login.jsp
If, in the process, there is some NullPointerException, it will check this exceptions in global-exception-mappings and if present, will return the corresponding result string.
The application then navigates to the corresponding URL mapped with that result string i.e. /error.jsp

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.