Back to: Java Struts Tutorials
Struts 2 Exception Handling with Examples
In this article, I am going to discuss Struts 2 Exception Handling with Examples. Please read our previous article where we discussed Struts 2 Type Conversion.
What is Exception Handling in Struts 2?
Exception handling is a programming concept and a mechanism employed in most modern programming languages to manage and deal with unexpected or exceptional situations that may occur during the execution of a program. These exceptional situations are often referred to as “exceptions.”
An exception is an event that interrupts the normal flow of a program’s execution, typically caused by errors, runtime faults, or unusual conditions that the program may encounter during its operation. Examples of exceptions include division by zero, accessing an invalid memory address, file not found, network errors, and more.
Goals of Exception Handling
The primary goals of exception handling are:
- Error Detection: Exception handling allows the program to detect and identify errors and exceptional situations as soon as they occur.
- Error Propagation: When an exception is encountered, the program can propagate the information about the exceptional situation back through the call stack until an appropriate exception handler is found to deal with it.
- Separation of Error Handling Logic: Exception handling separates the error handling logic from the normal flow of the program, improving the program’s clarity and maintainability.
- Graceful Recovery: It enables the program to gracefully recover from certain exceptional situations and continue executing instead of abruptly terminating.
In most programming languages, exception handling involves the following basic components:
- Throwing an Exception: When an exceptional situation occurs in the program, it throws an exception. This is typically done using the throw statement or a specific function provided by the language.
- Catching an Exception: To handle exceptions, code blocks (exception handlers) are defined to catch specific types of exceptions. This is accomplished using the try-catch or try-except construct in most languages.
- Exception Classes: Exceptions are represented as objects of specific exception classes. These classes encapsulate information about the exceptional situation and may contain details about the error, such as error codes, messages, or stack traces.
Struts 2 provides an easier method to handle exceptions.
How to Implement Exception Handling in Struts 2?
Step 1: Create a new maven project in Eclipse. We will use Maven to manage the dependencies of struts2. This way, we do not have to import JARs.
Remember to set the packaging to war. This is because we shall be deploying a web application.
Finally, click on the finish button to create the project. The following project directories need to be created:
Step 2: Modify pom.xml to add the required dependencies and the build configuration:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.dotnet</groupId> <artifactId>strutex</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>6.1.2.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>6.1.2.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts-taglib</artifactId> <version>1.3.10</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
Step 3: In the src/main/webapp directory, create a new file called index.jsp. This file asks the user for their name. Add the following content to the file:
<%@ 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>Hello World</title> </head> <body> <form action = "hello"> <label for = "name">Enter your name: </label> <input type = "text" name = "name"/> <br/> <input type = "submit" value = "Say Hello"/> </form> </body> </html>
Step 4: In the src/main/webapp directory, create a new file called success.jsp. This file displays the user’s name. Add the following content to the file:
<%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = "name"/> </body> </html>
Step 5: In the src/main/webapp directory, create a new file called error.jsp. This file is displayed when the program faces an exception. Add the following content to the file:
<%@ 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> An error occurred! </body> </html>
Step 6: In the src/main/java directory, create a new file called HelloWorldAction.java. The file contains the Java action code. Add the following content to the file:
package com.dotnet; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() { //NullPointerError String x = null; x.charAt(0); return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Note that an exception is thrown on purpose. This is the exception that needs to be caught.
Step 7: In the src/main/resources directory, create a new file called struts.xml. The file is responsible for configuring struts2. Add the following content to the file:
<?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.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "HelloWorldAction" class = "com.dotnet.HelloWorldAction" method = "execute"> <exception-mapping exception = "java.lang.NullPointerException" result = "error" /> <result name = "success">/success.jsp</result> <result name = "error">/error.jsp</result> </action> </package> </struts>
This file tells struts 2 to display the error page whenever the NullPointerException is thrown.
Step 8: In the src/main/webapp directory, create a new directory called WEB-INF. In this directory, create a new file called web.xml. This file is responsible for implementing struts2 in the web application. Add the following content into the file:
<?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/web-app_3_0.xsd" id="apache-struts-config-example" version="3.0"> <display-name>Struts Config XML</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Step 9: Compile and execute the program on the Tomcat server. The following page must open in your default web browser:
Enter any name. Because we throw a NullPointerExcpetion on purpose, the following page will be visible:
Congratulations! You now know how to implement exception handling in struts2!
In the next article, I am going to discuss Struts 2 Annotations with Examples. Here, in this article, I try to explain Struts 2 Exception Handling with Examples and I hope you enjoy this Struts 2 Exception Handling article.