Handling Exception in Struts 2

The exception handling is the common task in any Java based application. The Struts 2 framework provides the simple way to handle any uncaught exceptions generated by a web application and also provides robust exception handling, including the ability to automatically log any uncaught exceptions and redirect the user to a error web page. It works on exception interceptor which is part of default-stack in struts-default.xml file in any application.

There are two way to handle exception :

Global Exception Handling :

To enable global exception handling you need to add two nodes to struts.xml: global-exception-mapping and global-results. Using <global-exception-mappings> you can map global exception type for application and <global-results> is used for global result. If any exception occured in action and not configured the exception catching configuration with action configuration in struts.xml then framework searches in the global exception type and map with a result. This result type have to map using global result type. The global results mapping node relates the result value to a specific view page.

<global-results>
  <result name="null">/WEB-INF/pages/Fail1.jsp</result>
  <result name="excep">/WEB-INF/pages/Fail2.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping result="null" exception="java.lang.NullPointerException" />
<exception-mapping result="excep" exception="java.lang.Exception" />
</global-exception-mappings>

In the above code , if NullPointer exception is not mapped in the respective Action class then framework will search in the global exception. And if any other exception is not mapped in the Action class then framework will search in the global exception list. In both the case respective result type is configured and framework will search the result name in the global results and forward to the target view page.
In the above code Fail1.jsp will be executed if "NullPointerException" occured and Fail2.jsp will be executed if Any other exception will occured.

Exception Handling Per Action :

If you need to handle an exception in a specific way for a certain action you can use the exception-mapping node within the action node.
<action name="Calculator" class="techmyguru.actions.Calculator">
  <exception-mapping result="error"
    exception="java.lang.NumberFormatException" />
  <result>/WEB-INF/pages/Success.jsp</result>
  <result name="error">/WEB-INF/pages/Error.jsp</result>
</action>

In the above example, if NumberFormatException exception is uccured then custom error page Error.jsp will be executed else framework searches in the global exception list and execute the respective page using global-result type.

Lets demostrate how to handle exception type in Struts 2.
After running below example, user will get a form with two control and two hyper link. If enter correct number and submit it, then user will get addition of given number, if number is not parsable in number then NumberFormatException will occured and execute Error.
If user click first hyperlink, the action will throw NullPointerException and exception will be trap through global exception and execute Fail1.jsp
If user click second hyperlink, the action will throw NumberFormatException and exception will be trap through global exception and execute Fail2.jsp

Follow the following steps to create this project :

Step 1: Create a Dynamic Web Project in eclipse - "Struts2Exception".

Step 2: Edit deployment descriptor web.xml. [ Click here If you are not familiar with Struts2 application environment setup in Eclipse. ]

Step 3: The Struts2 jar files required in WEB-INF\lib folder in your project. Please read Readme.txt file in the attached source code for more details.

Step 4: Create a View page index.jsp :
<%taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<s:form action="Calculator" method="post">
<s:textfield label="Enter a number" name="num1"/>
<s:textfield label="Enter second number" name="num2"/>
<s:submit label="CalculateSum"/>
</s:form>
<hr>
NullPinterException example -  
<a href="<s:url action="Action1"/>">ActionLink1</a><br>
<br>
Global Exception NumberFormatException 
<a href="<s:url action="Action2"/>">ActionLink2</a><br>
</body>
</html>

Step 5: Create action class Calculator.java :
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class Calculator extends ActionSupport {
private String num1,num2;
private String message="";
// getter and setter methods
@Override
  public String execute() throws Exception {
  int n1=Integer.parseInt(num1);
  int n2=Integer.parseInt(num2);
  int sum=n1+n2;
  setMessage(""+sum);
  return SUCCESS;
  }
}
Action perform addition of two number and store result is message variable, If nunber is not parsed in int, it will throw NumberFormatException.

Create action class Action1.java :

package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class Action1 extends ActionSupport {
  @Override
  public String execute() throws Exception {
    String str = null;
    System.out.println(str.charAt(3));
    return SUCCESS;
  }
}
The Action1 will throw NullPointerException.

Create action class Action2.java :
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class Action2 extends ActionSupport {
  @Override
  public String execute() throws Exception {
    int sum=Integer.parseInt("10")+Integer.parseInt("10a");
  return SUCCESS;
  }
}
The Action1 will throw NumberFormatException.

Step 6: Configure Action in struts.xml file :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
  <constant name="devMode" value="true" />
  <package name="default" extends="struts-default">
    <global-results>
      <result name="null">/WEB-INF/pages/Fail1.jsp</result>
      <result name="excep">/WEB-INF/pages/Fail2.jsp</result>
    </global-results>
    
    <global-exception-mappings>
      <exception-mapping result="null"
        exception="java.lang.NullPointerException" />
      <exception-mapping result="excep" exception="java.lang.Exception" />
    </global-exception-mappings>

    <action name="Calculator" class="techmyguru.actions.Calculator">
      <exception-mapping result="error"
        exception="java.lang.NumberFormatException" />
      <result>/WEB-INF/pages/Success.jsp</result>
      <result name="error">/WEB-INF/pages/Error.jsp</result>
    </action>
    <action name="Action1" class="techmyguru.actions.Action1">
      <result name="success">/Success1.jsp</result>
    </action>

    <action name="Action2" class="techmyguru.actions.Action2">
      <result name="success">/WEB-INF/pages/Success1.jsp</result>
    </action>
  </package>
</struts>
In struts.xml, The NumberFormatException is mapped with Calculator action class. If NumberFormatException will occured in Calculator action the Error.jsp will be executed.
And in Action1 NullPointerException and in Action2 NumberFormatException will be occured and both the exceptions are maped through global-exception. The global exception raise respective result and this result is configured through global-result with respective JSP page.

Step 7: Create target View page Success.jsp :
<%taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h2>
The sum of 
<s:property value="num1"/> and 
<s:property value="num2"/> is 
<s:property value="message"/>
</h2>
<hr>
<a href="index.jsp">Try Again</a>
</body>
</html>
The Success.jsp page will be executed if both the numbers are parsable in int format.

Create error page Error.jsp :
<%taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h1>Unexpected error orrurred</h1>
<p><font color="red">Please report this error to system administrator</font></p>
<h3>Error Message</h3>
<s:actionerror /><br>
Exception object transfered to valuestack <s:property value="[0].top"/><br>
<s:property value="%{exception.message}"/>
<hr/>
<h3> Technical Details</h3>
<s:property value="%{exceptionStack}"/>
</body>
</html>
This page will be executed if the input numbers are not parsable in int format.

Create target View page Success1.jsp :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
<h2> If you see this page, it means no wexception in action class</h2>
</body>
</html>


Create error page Fail1.jsp :
<html>
<body>
<h1>Fail </h1>
<h1>Unexpected error orrurred</h1>
<p><font color="red">Please report this error to system administrator</font></p>
<h3>Error Message</h3>
<s:actionerror /><br>
Exception object transfered to valuestack <s:property value="[0].top"/><br>
<s:property value="%{exception.message}"/>
<hr/>
<h3> Technical Details</h3>
<s:property value="%{exceptionStack}"/>
</body>
</html>
The Fail1.jap will be executed if Action1 throws NullPointerException.

Create error page Fail2.jsp :
<html>
<body>
<h1>Fail 2</h1>
<h1>Unexpected error orrurred</h1>
<p><font color="red">Please report this error to system administrator</font></p>
<h3>Error Message</h3>
<s:actionerror /><br>
Exception object transfered to valuestack <s:property value="[0].top"/><br>
<s:property value="%{exception.message}"/>
<hr/>
<h3> Technical Details</h3>
<s:property value="%{exceptionStack}"/>
</body>
</html>
The Fail1.jap will be executed if Action1 throws NumberFormatException.

Step 8: Verify the project directory structure.
configure exception in Struts2

Step 9: Run the project and get output.
configure exception in Struts2

Input incorrect numbers and click submit, user will get below screen :
configure exception in Struts2
Input correct numbers and click submit, user will get below screen :

configure exception in Struts2
Click first hyperlink and get below error page :

configure exception in Struts2
Click first hyperlink and get below error page :

configure exception in Struts2

Previous Download Source Code Next

Comment by : Sam October 3rd, 2015
Comment : From the way u r say *.do, I assume u r using strtus. Struts forms have an associated form bean. These beans store data in them when is request is sent to back end.Now try this approach:1. Create ur J

Comment by : sathish November 26th, 2013
Comment : it is very useful to me


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code