Struts 2 exception Interceptor

In the struts web application, an exception may occur at any point. This exception should be handled properly. The global exception handling feature is provided by struts. With the help of this, we can display the global result to the user. It will redirect to an error page, when an exception is occurred.

Struts exception Interceptor Example:

In order to get input from the user create index.jsp file:

The index.jsp page is created in order to take input from user. User have to enter the name and password and then after clicking on the login button, it will redirect to the next resource.

<%@ taglib uri="/struts-tags" prefix="s"  %>
<s:form action="login">
<s:textfield name="name" label="Enter Name"></s:textfield>
<s:password name="password" label="Enter Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>

Create login-success.jsp file to denote success:

login-success.jsp page displays welcome and username on success.

<%@ taglib uri=”/struts-tags” prefix="s"  %>


Welcome, <s:property value="name"/>

Create login-error.jsp file to denote failure:

login-error.jsp page displays Sorry, username or password error! on failure.

<p>Sorry, username or password error!</p>
<jsp:include page="index.jsp"></jsp:include>

Create exceptionhandler.jsp file for exception handling:

This is the global result jsp page that displays the exception handling message along with Sorry, an exception occured! Message. When an exception occurs automatically this page is called.

<p>Sorry, an exception occured!</p>
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:property value="exception"/>

Create the action class Login.java:

This is the action class. It contains two fields name and password with their getter and setters. It contains the execute method which includes code throwing the exception that is divide by zero exception. On success when the password matches it will redirect to login-success.jsp page otherwise on error it will redirect to login-error.jsp.

public class Login
{
        private String name,password;


         public String getName() 
        {
             return name;
        }   


        public void setName(String name)
       {
  this.name = name;
        }


        public String getPassword() 
       {
return password;
        }


        public void setPassword(String password)
       {
this.password = password;
        }
        public String execute()
        {
             int a=10/0;
  if(password.equals("admin"))
            {
return "success";
  }
             else
            {
return "error";
}
       }


}

web.xml file is created inside WEB-INF folder in WebContent folder:

J2EE configuration file i.e., web.xml file defines how elements are processed. The entry of FilterDispatcher is done in the web.xml file. This file is created in WebContent->WEB-INF folder. /* specifies all urls will be parsed. This task is done by struts filter.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>StrutsExecInteceptor</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
      <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>

Construct struts.xml file:

In the struts.xml file, make the entry of the exception handling code. Also, specify the action class Login and link for it and result pages. The result determines what browser will display after the execution of the action. Results have optional names like success and error. The global-result specifies the global result. The global-exception-mappings show exception mapping for each action.

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


<global-results>
<result name="exhandler">exceptionhandler.jsp</result>
</global-results>


<global-exception-mappings>
<exception-mapping result="exhandler" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>


<action name="login" class="Login">
<result name="success">login-success.jsp</result>
<result name="error">login-error.jsp</result>
</action>


</package>
</struts>

Output:

In order to run the application, right-click on the project -> Click on the option Run As -> then select Run on Server. It will show two labels for entering the name and password and the login button. Enter the name and password admin and then click on the login button.

Struts exception Interceptor

As the name is Sanket and the password is admin it will return success. But in execute method an exception occurs by the code int a= 10/0. This will generate an exception and then it will redirect to exceptionhandler.jsp which will display Sorry, an exception occurred! and it will return exception / by zero i.e., Arithmetic Exception.

Struts exception Interceptor

Then comment the code generating exception i.e., int a= 10/0, and run the application. Enter any name and password as admin. Click on the login button.

Struts exception Interceptor

As the correct name and password are entered by the user, execute method will return success and redirect to the login-success.jsp page and display Welcome, name.

Struts exception Interceptor

Again run the application. This time enter any name and wrong password 12345678.

Struts exception Interceptor

As the password is wrong, it will return an error and redirect to login-error.jsp and display a message Sorry, username or password error! and again display textfield to enter name and password.

Struts exception Interceptor

Related Topics

Struts 2 prepare Interceptor

In order to implement prepare interceptor in the struts web application, the class must implement a Preparable interface and override the prepare method along with the execute method. While executing...

4 minutes read.

Struts 2 Custom Interceptor

Custom Interceptor can be implemented in struts application by implementing Interceptor interface. We have to override all three life cycle methods. The Interceptor interface itself provides methods to implement custom...

4 minutes read.

Struts 2 url tag

The url tag in struts is used to create url as a text. It creates url as a text string. Struts Data tags- url tag Example: Create the index.jsp file showing the...

4 minutes read.

Struts 2 ValueStack

Struts ValueStack: The value stack in the struts application is nothing but a stack that contains a collection of objects such as action object, model object, temporary object, and named object. 1....

5 minutes read.

Struts 2 If Else tag

In the struts, web application, the If Else tag is used to check among multiple conditions. The code along with the right condition will be executed as the result. Struts Control...

4 minutes read.

Struts 2 include tag

The include tag in struts is used to include some other resource like other jsp or servlet file in the existing jsp page. In the struts web application, it is...

4 minutes read.

Struts 2 param tag

The param tag in struts is used to set values of the variable in other tags like include and bean tag. It is used to parametrize other tags. Struts param...

4 minutes read.

Struts 2 bean tag

The bean tag in struts is used to set values of the variable by creating the new instance of an object. It allows you to set the values and then...

4 minutes read.

Struts 2 Email Validator

In the struts, web application, an email validator is used to check whether the entered email by the user is valid or not. Parameter defined with email validator is: fieldName: It...

5 minutes read.

Struts 2 Date Validator

In the struts web application, a date validator is used to check whether the entered date is within the specified range. Three parameters defined with date validator are: fieldName: It is...

5 minutes read.

Struts 2 Fetch Records From Database

The database can be connected with struts applications to retrieve data using JDBC. Struts-Fetch Records From Database example: Create the database and create the table in it: Create any database using sql command...

4 minutes read.

Struts 2 push tag

Struts Data tags- Push tag Example: The push tag in struts2 is used to set the value and maintain it on top of the stack. It makes the value easier to...

4 minutes read.

Struts 2 Datetimepicker tag

The datetimepicker tag in struts is used when the user needs to take date input. It displays a calendar icon. When we click on this icon, it allows us to...

4 minutes read.

Struts 2 Installation and Example

Struts Installation: For developing struts applications, you need to have java installed on your machine. For verifying that Java is already installed on your machine, use the following commands: For Windows: Open Command line.Type...

4 minutes read.

Struts 2 URL Validator

In the struts, web application, a url validator is used to check whether the entered url is valid or not. One parameter defined with url validator is: fieldName: It is used...

4 minutes read.

Struts 2 Generator tag

The generator tag in struts is used to iterate over the collection of elements provided by the val attribute. It allows us to iterate through every element and perform the...

4 minutes read.

Struts 2 execAndWait interceptor

The execute and wait interceptor is also known as execAndWait interceptor. The intermediate result is displayed with the help of this interceptor. The wait result is specified in the struts.xml...

4 minutes read.

Struts 2 Database Access

The database can be connected with struts applications to store and retrieve data using JDBC. Struts Database Access example: Create the database and create the table in it: Create database stuser;  // create...

4 minutes read.

Struts 2 Form tag

In struts, web application various UI elements tag are used to create forms like HTML. Various struts UI tags like form tag, textfield tag, password tag, textarea tat, checkbox tag,...

6 minutes read.

Struts 2 Multiple Configuration file

In order to create large struts web applications, multiple configuration files are used. Multiple configuration files are included in struts.xml file using include sub-element. Struts- Multiple Configuration File Example- To get input...

5 minutes read.