Struts2 Exception Handling Example Tutorial

Filed Under: Struts 2

Exceptions are common in any application. We try to catch it and process it but sometimes our application is not able to process it and it’s thrown to the container. Struts2 provides a robust mechanism through which we can provide customized response to client whenever any exception is thrown by the application.

We know that Struts2 interceptors are like servlet filters that provide pre-processing of request and post-processing of application response. Struts2 provides exception handling support through com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor interceptor. This interceptor is part of basicStack and defaultStack interceptors stack, so we don’t need to configure them for our application usage.

We can provide exception handling at package level through global-exception-mappings and global-results and we can use exception-mapping in action mappings for action level exception handling. We need to provide result pages to use for different exception scenarios. Let’s try to understand it’s usage with a simple application.

We will create a dynamic web project and then configure it as Maven project. Our project structure looks like below image.

Struts2-Exception-Handling-Project

Web Application Configuration for Struts2

Add struts2 dependency in pom.xml file like below.


<dependencies>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.15.1</version>
	</dependency>
</dependencies>

Struts2 filter configuration in deployment descriptor file.

web.xml


<?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"
	version="3.0">
	<display-name>Struts2Exception</display-name>
	
	<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>

Action Classes

We will create few action classes whose only purpose will be to throw some exceptions.


package com.journaldev.struts2.exception;

import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute(){
		throw new NullPointerException("Mandatory data missing");
	}
}

package com.journaldev.struts2.exception;

import java.io.IOException;

import com.opensymphony.xwork2.ActionSupport;

public class MySpecialAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws IOException{
		throw new IOException("IOException occured");
	}
}

Struts2 Configuration

We are configuring package level exception handling and action level exception handling in struts.xml configuration file.

struts.xml


<?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="struts.devMode" value="true"></constant>

<constant name="struts.convention.result.path" value="/"></constant>

<package name="user" namespace="/" extends="struts-default">

<global-results>
	<result name="exception">/exception.jsp</result>
	<result name="runtime_exception">/runtime_exception.jsp</result>
	<result name="error">/error.jsp</result>
</global-results>

<global-exception-mappings>
	<exception-mapping exception="java.lang.Exception" result="exception"></exception-mapping>
	<exception-mapping exception="java.lang.Error" result="error"></exception-mapping>
	<exception-mapping exception="java.lang.RuntimeException" result="runtime_exception"></exception-mapping>
</global-exception-mappings>

	<action name="myaction" class="com.journaldev.struts2.exception.MyAction">
	</action>
	<action name="myspecialaction" class="com.journaldev.struts2.exception.MySpecialAction">
	<exception-mapping exception="java.io.IOException" result="login"></exception-mapping>
	<result name="login">/error.jsp</result>
	</action>
</package>


</struts>

Notice that we need to define global result pages for global level exception mapping to result pages. For action level exception handling, we need to define result page in action mapping.

Since there is no exception result pages mapped for MyAction and it’s throwing NullPointerException, the closest base class with exception mapping is RuntimeException, so it should return runtime_exception.jsp page.

For MySpecialAction throwing IOException, the result page is defined and it should return error.jsp page.

Let’s write these JSP pages and confirm this behavior.

JSP Pages

runtime_exception.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Runtime Exception Page</title>
</head>
<body>
Some Runtime Exception Occured!!<br><br>

Runtime Exception Name: <s:property value="exception"/><br><br>

Runtime Exception Stack Trace: <br>
<s:property value="exceptionStack"/>
</body>
</html>

error.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error Page</title>
</head>
<body>
Some Error Occured!!<br><br>

Error Name: <s:property value="exception"/><br><br>

Error Stack Trace: <br>
<s:property value="exceptionStack"/>
</body>
</html>

Notice that we have defined exception.jsp as result page for any java.lang.Exception but since there was no exception that is the closest match to this, it’s not used.

Run the Application

Now when we run the application, we get following pages as response confirming the exception handling behavior.

Struts2-Action-ExceptionMapping

Struts2-globalexception

That’s all for Exception Handling in Struts2 applications, you can download the project from below link and play around with it for more learning.

Comments

  1. soni says:

    struts.xml

    Home.jsp
    index.jsp

    LoginValidate.java
    package com.rcpl;

    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.util.logging.Logger;
    import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts2.dispatcher.SessionMap;
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.ServletResponseAware;

    public class LoginValidate extends ActionSupport implements ServletRequestAware,sessionAware{
    SessionMapsessionMap;
    private String user;
    private String password;
    HttpServletRequest request;
    public SessionMap getSessionMap() {
    return sessionMap;
    }

    public void setSessionMap(SessionMap sessionMap) {
    this.sessionMap = sessionMap;
    }

    public String getUser() {
    return user;
    }

    public void setUser(String user) {
    this.user = user;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }
    public void setServletRequest(HttpServletRequest hsr){
    request = hsr;
    }
    public void setSession(Mapmap){
    sessionMap = (SessionMap)map;
    }
    @Override
    public String execute(){
    if(getUser().equals(getPassword())){
    sessionMap.put(“u”,user);
    request.setAttribute(“u”,user);
    return SUCCESS;

    }else{
    return ERROR;
    }
    }

    }

    index.jsp

    Struct Page

    Hello Login !

    Home.jsp

    JSP Page

    Hello World!

  2. sarath gowd thota says:

    do we have exception handling mechanism before struts2.3?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages