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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Struts 2 Interceptors Example

Struts 2 Interceptors Example

Meyyappan Muthuraman user avatar by
Meyyappan Muthuraman
·
Jun. 15, 12 · Tutorial
Like (1)
Save
Tweet
Share
107.60K Views

Join the DZone community and get the full member experience.

Join For Free

In this example you will see how the interceptors are invoked both before and after the execution of the action and how the results are rendered back to the user. Let's understand this with the help of the following diagram.

The following actions happen in a sequence when a request comes to the Struts 2 framework.

  • Framework first finds which Action class to invoke for this request and discovers the interceptors associated with the action mapping.
  • Now the Framework creates an instance of ActionInvocation and calls its invoke() method. At this point the Frameworks hands the control over to the ActionInvocation for further processing of the request.
  • ActionInvocation is the one which encapsulates the action and the associated intercteptors. ActionInvocation knows in which sequence the interceptors should be invoked.
  • ActionInvocation now invokes the intercept() method of the first interceptor in the stack. We will understand this with the help of an example. Our example is very simple it uses only one interceptor for logging details.
  • The LoggingInterceptor's intercept() method contains the following code.
public String intercept(ActionInvocation invocation) throws Exception
{
    //Pre processing
    logMessage(invocation, START_MESSAGE);

    String result = invocation.invoke();

    //Post processing
    logMessage(invocation, FINISH_MESSAGE);

    return result;
}
  • As you can see, first the logMessage() method is called and the message is logged, this is the pre processing done by the logger interceptor, then the invoke() method of the ActionInvocation is again called, this time the ActionInvocation will call the next intercetor in the stack and this cycle will continue till the last interceptor in the stack.
  • After the execution of all the interceptors the action class will be invoked. Finally a result string will be returned and the corresponding view will be rendered. This is the normal flow of events.
  • But what if an validation error occurs, in this case the request processing will be stopped. No further interceptors will be invoked. Action will not be executed. The control flow changes, now the interceptors executed so far will be invoked in the reverse order to do the post processing if any and finally the result will be rendered to the user.
  • Let's come back to the normal flow. In our case the logger interceptor is the only interceptor in the stack, so after logging the "START_MESSAGE", the ActionInvocation's invoke() method will invoke the action. Our action simply returns "success", then again the logger interceptor will be invoked to do the post processing, this time the "FINISH_MESSAGE" is logged and the result is returned. Based on the result the corresponding view will be rendered to the user.

We get the following benefits by using the interceptors.

  • Extremely flexiable.
  • Cleaner and focused Action classes.
  • Provides code readability and code reuse.
  • Testing process becomes easier.
  • We can add only the interceptors we need to the stack and customising the action processing for each request.

Now lets see the flow of the example. In the index.jsp page we forward the request to the "TestLogger" URL.

<META HTTP-EQUIV="Refresh" CONTENT="0;URL=TestLogger.action">

The TestLogger URL is mapped to the TestLoggerAction class in the struts.xml file.

<!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">
        <action name="TestLogger" class="vaannila.TestLoggerAction">
            <interceptor-ref name="logger" />
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>       

Based on the mapping in the XML configuration file the user will be forwarded to the success page.

The following log messages are logged in the console.

package vaannila;

public class TestLoggerAction {

    public String execute()
    {
        System.out.println("Inside Action");
        return "success";
    }
}

Hope you understood the concept of interceptors. You can download this example by clicking the Download link below.

Source :Download
Source + Lib :Download
Requests Processing Framework Flow (web browser) Execution (computing) POST (HTTP) Download Concept (generic programming)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Gentle Introduction to Kubernetes
  • Host Hack Attempt Detection Using ELK
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • Keep Your Application Secrets Secret

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: