Struts 2 Interceptors

shape Description

Struts 2 Interceptors is an object, which is invoked (executed) the pre-processing request and post-processing request. Interceptors are used to perform the validations, exceptions handling and display the result in between the execute() method. Struts 2 Interceptors execution is same as the servlet filter execution type.The advantage of Interceptors is, One can run the application using validations, after sometimes remove the validations on that application, and one cannot deploy the application in the server again. So, directly start the server application and execute. Following are the default interceptors of Struts 2.

shape More Info

Interceptors are executed, whenever the request is coming to the container at that time container first will check to use any interceptors to be executed and execute the Action class execute(). This process is executed by using invoke().invoke() contain ActionInvocation interface object.

String interceptor =ActionInvocation.invoke(); 

If one have to write the custom Interceptors class, that class will be extended to AbstractInterceptor class

By using interceptors in the application, one can use the tag in struts.xml file.


<interceptor-ref>
params
</interceptor-ref>
<interceptor-ref>
interceptor class reference id
</interceptor-ref>
<interceptor-ref>
timer
</interceptor-ref>


shape Example

For example, let’s take one interceptor class and execute.

shape Step 1

Create the project directory structure.

shape Step 2

Add the jar files in lib folder. Struts2 jar files and servlet-api.jar.

shape Step 3

Create the View pages and forwarded the request to Action class.
index.jsp

<%@ taglib uri="/struts-tags" prefix="s" %>
  <s:form action="employee"> 
      <s:textfield name="id" label="Employee Id">
  </s:textfield> 
      <s:submit value="submit">
  </s:submit> 
  </s:form>

The s:textfield is used to create a HTML input textbox.


shape Step 4

To map the URL pattern in a web.xml file.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xml ns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
      <filter-name>
        struts2
      </filter-name>
      <filter-class> 
         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 
      </filter-class>
   </filter>
   <filter-mapping>
      <filter-name>
       struts2
      </filter-name>
      <url-pattern>
       /*</url-pattern>
   </filter-mapping>
</web-app>

Here make sure that filte-name should be same.

shape Step 5

Create the interceptor class and Action class.
EmployeeInterceptor.java

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

public class EmployeeIntercepter extends AbstractInterceptor
{
 
  public String intercept(ActionInvocation invocation)throws Exception
  {

   /* let us do some pre-processing */
   String output = "Pre-Processing interceptor"; 
    System.out.println(output);

   /* let us call action or next interceptor */
   String result = invocation.invoke();

  /* let us do some post-processing */
   output = "Post-Processing interceptor"; 
      System.out.println(output);

    return result;
  }
 }
 

Here used invocation.invoke() method to invoke action.
EmployeeAction.java

package com.itoolsinfo;

public class EmployeeAction 
{
 private int id;

 public int getId()
  {
 return id;
 }

 public void setId(int id) 
 {
 this.id = id;
 }
 public String execute()
 {
 System.out.println("It is the main class execute method");
 return "success";
 
 }
}

Here used Set and Get methods to perform on id.

shape Step 6

Configure the interceptor class and Action class in struts.xml file.
struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
  <package name="default" extends="struts-default">

    <interceptors>
      <interceptor name="myinterceptor" class="com.iquickinfo.EmployeeInterceptor"/>
    </interceptors>
    <action name="employee" class="com.itoolsinfo.EmployeeAction" method="execute">
        <interceptor-ref name="params"/>
        <interceptor-ref name="myinterceptor" />
        <result name="success">
         /success.jsp
     </result>
    </action>
 </package>
</struts>

Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class.

shape Step 7

Forward the response into the browser.
success.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   </head>
   <body>
     Itoolsinfo Employee Details successfully saved.

     Employee Id :<s:property value="id">
</br>
</body>
</html>

The property tag is used to get the property value from a class, which will default to the current Action class property if none is specified.

shape Output

Run the application in server, the output is displayed as below.
Enter the employee id and click on submit button, then the output is displayed on console.
Display the output in browser.

Summary

shape Key Points

  • Struts 2 Interceptors are pluggable
  • Struts 2 Interceptors are same like Servlet fileters.
  • Internalization task will be performed by interceptors.