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" onclick="history.back()">
 </form>
</body>
</html>
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 >>







No comments:

Post a Comment