exceptions thrown by Struts2
Handling exceptions effectively in a Struts2 application involves configuring global exception handling mechanisms and implementing specific exception handling in actions or interceptors. Here’s an explanation followed by a Java example:
Table of Contents
Explanation
Struts2 provides several ways to handle exceptions:
- 1. Â Global Exception Handling:
- Configure global exception mapping in struts.xml to handle uncaught exceptions across the application.
- Define custom error pages or redirect to specific actions to handle different types of exceptions uniformly.
- 2. Â Action-specific Exception Handling:
- Implement exception handling directly in action classes using try-catch blocks to handle specific exceptions locally.
- Redirect users to appropriate error pages or perform recovery actions based on the exception type.
- 3. Â Interceptor-based Exception Handling:
- Use interceptors to intercept exceptions thrown during the execution of actions.
- Implement custom interceptors to log exceptions, handle specific exceptions, or redirect to error pages.
Java Example
Here’s how you can configure global exception handling in Struts2 and handle exceptions in action classes:
Global Exception Handling (struts.xml)
xml
<struts>
<package name="default" extends="struts-default">
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error" />
<exception-mapping exception="java.lang.RuntimeException" result="error" />
</global-exception-mappings>
<global-results>
<result name="error">/error.jsp</result>
</global-results>
</package>
</struts>
Handling Exceptions in Action Class
java
package com.example.actions;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport {
private int userId;
private User user;
public String execute() {
try {
user = userService.findUserById(userId);
if (user == null) {
throw new RuntimeException("User not found");
}
return SUCCESS;
} catch (Exception e) {
addActionError("An error occurred: " + e.getMessage());
return ERROR;
}
}
// Getter and Setter for userId and user
}
In this example:
- Global Exception Handling: Â Exceptions of type java.lang.Exception and java.lang.RuntimeException are mapped to the result “error” in struts.xml. The result directs to /error.jsp where appropriate error handling can be done.
- Action-specific Exception Handling: Â The execute() method in MyAction catches exceptions (RuntimeException in this case) and adds an error message to the action errors (addActionError). It then returns “error” as the result, which will be handled globally as per the configuration.
By combining global exception handling in struts.xml with local exception handling in action classes, you can effectively manage and respond to exceptions thrown by your Struts2 application, ensuring a robust and user-friendly experience.