Struts2

Struts 2 Exception Handling

In this chapter we will learn about the exception handling in struts2 framework. If any exception occur between the code it redirected to the dedicated page whatever you define or map into the configuration file of struts2.

In our web application, there might occur exception. To overcome this problem, struts 2 provides a mechanism of global exception handling where we can display a global result to the user.

Example of Exception Handling in struts 2 –

Struts makes the exception handling easy by the use of the “exception” interceptor. The “exception” interceptor is included as part of the default stack, so you don’t have to do anything extra to configure it. It is available out-of-the-box ready for you to use. Let us see a simple Hello World example with some modification in LoginAction.java file. Here we purposely introduced a NullPointerException in our LoginAction action code.

package com.dineshonjava.struts2.login;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
@SuppressWarnings("serial")
public class LoginAction  extends ActionSupport{
 private String username;
    private String password;
    private String userid;
    
    public String execute(){
        String x = null;
        x = x.substring(0);
        return SUCCESS;
     }
    
 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getUserid() {
  return userid;
 }

 public void setUserid(String userid) {
  this.userid = userid;
 }
 
}

Let us keep the content of Login.jsp as follows:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 - Login Application | dineshonjava.com</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<font color="red"><s:actionerror /></font>
<s:form action="welcome.action" method="post">
    <s:textfield name="username" key="label.username" size="20" />
    <s:password name="password" key="label.password" size="20" />
    <s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Let us keep the content of Welcome.jsp as follows:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
 
<body>
    <h2>Hello Welcome , <s:property value="username" />...! Dineshonjava.com</h2>
    
</body>
</html>

Your struts.xml should look like:

<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
    <package name="default" extends="struts-default" namespace="/">
        <action name="welcome" class="com.dineshonjava.struts2.login.LoginAction">
            <result name="success">/Welcome.jsp</result>
            <result name="error">/Login.jsp</result>
        </action>
    </package>
   
</struts>

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/Login.jsp.

This will give you following screen:

Enter a value of user name and password and submit the page. You should see the following page:

http://localhost:8080/doj/welcome.action;jsessionid=8043CCAD28F8A538283A322BFF761C11

As shown in the above example, the default exception interceptor does a great job of handling the exception. Let us now create a dedicated error page for our Exception. Create a file called globalerror.jsp with the following contents:
globalresult.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
   This is my custom error page
   <form>
     <input type="button" value="back" >

For exception handling, we specify the global-result and global-exception-mappings in the 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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
  
  <package name="default" extends="struts-default" namespace="/">
  <global-results>
  <result name="myresult">/globalresult.jsp</result>
 </global-results>
 
 <global-exception-mappings>
  <exception-mapping result="myresult" exception="java.lang.Exception"></exception-mapping>
 </global-exception-mappings>

    
        <action name="welcome" class="com.dineshonjava.struts2.login.LoginAction">
            <result name="success">/Welcome.jsp</result>
            <result name="error">/Login.jsp</result>
        </action>
    </package>
   
</struts>

The global-results sub-element of package specifies the global-result for this package.

The result sub-element of global-result specifies the result page that will be rendered to the user as a view.

The global-exception-mappings sub-element of package specifies the exception mapping for all the actions of this package.

The exception-mapping sub-element of global-exception-mapping maps the given result for the given exception type. In this example, we are using the Exception which the parent of many exception classes such as IOException, ArithmeticException etc. It means if any exception occurs, specified result will be invoked.

Note: Notice that global-results must be specified before global-exception-mappings as we are using global result in global-exception-mappings.

As shown in the example above, now we have configured Struts to use the dedicated globalerror.jsp for the NullPointerException. If you rerun the program now, you shall now see the following output:

 

Download SourceCode
Struts2Exception.zip

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago