Struts 2 Exception Configuration

Struts 2 simplifies the way we handle the exceptions. In the earlier version of Struts application, handling exceptions needs lot of work. In Struts 2, You can configure the exception type in the configuration file for the each action mapping and redirect to the custom error page. Here I have modified our hello world example to experiment exception handling. I have thrown SQlException from the action class which is configured in the configuration file with appropriate error page. Look at the below code to understand the exception handling.

1. Create Struts 2 Action


import java.sql.SQLException;

public class Struts2HelloWorldAction {
	private String userName;

	public String getUserName() {
		return userName;

	public void setUserName(String userName) {
		this.userName = userName;
	public String execute() throws SQLException{
		if (true){
			throw new SQLException();
		return "success";

2. Configure struts.xml File

exception-mapping element under action element will be used for configuring the exceptions. Note that this configuration is action level, so you can configure exception pages for each action which gives more control to the developers. You can define as many as error pages for your application. However, it is good practice to write a more generic exception page for your application.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "">
<constant name="struts.devMode" value="true" />
<package name="hello" extends="struts-default">
<action name="Welcome" class="" >
	<exception-mapping exception="java.sql.SQLException" result="error"/>
	<result name="success">Result.jsp</result>
	<result name="error">Error.jsp</result>

3. Create Error JSP

If there is any error is thrown from the action class, by default this error page will be redirected to the user. You can customize this page to display any custom details which will be meaningful to the users.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error Page</title>
This is a sample error page!!

4. Configure web.xml File

<?xml version="1.0" encoding="UTF-8"?>

5. Run The Application

If you access the application http://localhost:8080/Struts2App/Welcome.action. You would see the following output in your screen.

Struts 2 Exception Handling Example Screen

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!