DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Struts 2 Tutorial: Struts 2 Interceptors Tutorial with Example

Today we will explorer the world of Interceptors in Struts2. We will see what Interceptors are and how to configure them in a Struts2 based web application.

Viral Patel user avatar by
Viral Patel
·
Jan. 18, 10 · Tutorial
Like (0)
Save
Tweet
Share
116.10K Views

Join the DZone community and get the full member experience.

Join For Free

Welcome to Part-5 of 7-Part series where we are discussing different aspects of Struts2 Framework. In the previous article we saw how to integrate Tiles framework with Struts2.

Today we will explorer the world of Interceptors in Struts2. We will see what Interceptors are and how to configure them in a Struts2 based web application.

Struts 2 Tutorial List

  • Part 1: Introduction to Struts 2 Framework
  • Part 2: Create Hello World Application in Struts 2
  • Part 3: Struts 2 Validation Framework Tutorial with Example
  • Part 4: Struts 2 Tiles Plugin Tutorial with Example
  • Part 5: Struts 2 Interceptors Tutorial with Example
  • Part 6: Struts 2 File Upload and Save Example
  • Part 7: Struts 2 Ajax Tutorial with Example

Struts 2 Interceptors: Basics

Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
struts2 request processing lifecycle
The request processing lifecycle of Struts2 framework is pretty much discussed Part 1 – Introduction to Struts2 Framework.

  1. Request is generated by user and sent to Servlet container.
  2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
  3. One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
  4. Action is executed and the Result is generated by Action.
  5. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.

Thus the Struts2 Interceptors removes cross cutting tasks such as logging from action components and create cleaner separation of MVC.

Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application.

Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.

Our Goal

Our goal will be to create a customer interceptor MyLoggingInterceptor, which will log the request before any action is called. Also it will prints the Action class name and execution time of action in milliseconds.

Create Logging Interceptor

Create a java class MyLoggingInterceptor in package net.viralpatel.struts2.interceptors and copy following content into it.
struts2-logging-interceptors

package net.viralpatel.struts2.interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class MyLoggingInterceptor implements Interceptor{private static final long serialVersionUID = 1L;public String intercept(ActionInvocation invocation) throws Exception {String className = invocation.getAction().getClass().getName();long startTime = System.currentTimeMillis();System.out.println("Before calling action: " + className);String result = invocation.invoke();long endTime = System.currentTimeMillis();System.out.println("After calling action: " + className+ " Time taken: " + (endTime - startTime) + " ms");return result;}public void destroy() {System.out.println("Destroying MyLoggingInterceptor...");}public void init() {System.out.println("Initializing MyLoggingInterceptor...");}}

Configuring Interceptor in struts.xml

Once we have created an interceptor class, all we need to do is to configure it in struts.xml file and use it with actions.

To configure newly created interceptor, add following code in struts.xml

<interceptors><interceptor name="mylogging"class="net.viralpatel.struts2.interceptor.MyLoggingInterceptor"></interceptor><interceptor-stack name="loggingStack"><interceptor-ref name="mylogging" /><interceptor-ref name="defaultStack" /></interceptor-stack></interceptors>

This code has to be added after <result-types > tag in <package ></package>
Here we have configured a new interceptor mylogging with tag <interceptor >. Also note that we have defined an interceptor-stack with name loggingStack. This is to make sure Sturts2 calls all the default interceptors as well while calling our custom interceptor. This is very important as the validation logic will not work in our struts2 application if we ignore the default stack of interceptors.

We can make the new loggingStack as default interceptor stack or can configure it at each action level. In order to make it default stack, we should add following in struts.xml

<default-interceptor-ref name="loggingStack"></default-interceptor-ref>

Once we add above code in Struts.xml, the logginStack will be applied to all the actions in that package.

Also we may want to apply the custom interceptor stack to only certain actions. To do so, we must add interceptor-ref tag in action.

<action name="login"class="net.viralpatel.struts2.LoginAction"><interceptor-ref name="loggingStack"></interceptor-ref><result name="success" type="tiles">/welcome.tiles</result><result name="error">Login.jsp</result></action>

That’s All Folks

If we execute our StrutsHelloWorld application in Eclipse and see the console logs, we will find the log statements that we print in our interceptor.

Initializing MyLoggingInterceptor.........Before calling action: net.viralpatel.struts2.LoginAction....After calling action: net.viralpatel.struts2.LoginAction Time taken: 313 ms......Destroying MyLoggingInterceptor...

Download Source Code

Click here to download Source Code without JAR files (17KB)

Moving On

Today we saw what are Struts Interceptors and how to create a custom interceptor and configure it with a Struts2 based web application. In the next part we will see Struts2 File Upload Example.

application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Create and Edit Excel XLSX Documents in Java
  • Mr. Over, the Engineer [Comic]
  • Microservices Discovery With Eureka
  • Real-Time Stream Processing With Hazelcast and StreamNative

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: