Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Handling Exceptions in a Struts 2 Application

In this tutorial, we shall learn the process that allows us to carry out handling of exceptions by the use of the Struts 2 framework. We shall first learn about some amount of background information about Struts 2

For any application, exceptions tend to be pretty well known occurrences that pop up from time to time. The obvious response to any such exceptions is to make use of the language’s inbuilt exception handling mechanisms. The first step of such a stance includes that of catching an exception and then processing it according to the type of exception. However, very often, the inbuilt exception handling mechanism offered by the language might fail to process it, in which case, it will appear in the container. This is when an external framework can be used for handling of exceptions in a more comprehensive manner. So, we use Struts 2 to care of exception handling in this tutorial.

What is Struts 2?

Apache Struts 2 happens to be a framework for the development of web applications in Java Enterprise Edition. It is also open-source in nature and encourages the use of the MVC architecture.

Struts is known to offer an easy way for the handling of uncaught exceptions in applications and then further redirecting users to a dedicated error page. It is easily configurable and one can have different error pages for a variety of exceptions. Therefore, it supports a very robust mechanism to handle exceptions.

Use of interceptors

The use of interceptors is pretty much common in the Struts framework. In fact, this is exactly how exception handling gets a lot easier. Struts 2 interceptors are known to work like servlet filters that are basically known to deal with the pre-processing of requests and post-processing of application responses. The ‘exception’ interceptor is also something that is in the default stack of the application, so there is no need to configure it.

Types of exception handling in Struts 2

There are a few ways to handle exceptions in Struts 2. We shall take a look at them one by one.

Global Exception Handling

The Struts 2 framework can be used for specifying how the framework is to handle exceptions that are uncaught. These are specified in the struts.xml file.

In the case of global exception handling, the handling logic applies to all actions. In order to handle global exception handling, one needs to add two add two nodes to struts.xml. These are global-exception-mapping and global-results.

Listing 1. Global exception handling

<global-results>
     <result name="securityerror">/securityerr.jsp</result>
 <result name="error">/err.jsp</result>
</global-results> 
<global-exception-mappings>
 <exception-mapping exception= "org.apache.struts.register.exceptions.SecurityBreachException" result="securityerror" />
  <exception-mapping exception="java.lang.Exception" result="error" />
</global-exception-mappings>

Here, the global exception mapping tells the Struts 2 framework about what it required to be done if the if there is an uncaught exception of a certain type is thrown up in the application. Say, for example, SecurityBreachException is thrown but not caught, the Action class for Struts 2 will return “securityerror” as a result. Any other uncaught exception will result in “error”.

Also, the global results maps to the result value to a certain page. Here, “securityerror” causes the redirection of the user’s browser to securityerr.jsp page.

Exception Handling per Action

When there is a need to handling a certain action in a specific manner, the exception mapping node can be used with the action node.

Listing 2. Exception handling per action

<action name="actionspecificexception" class=" org.apache.struts.register.action.Register" method="throwSecurityException">
  <exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException"
       result="login" />
   <result>/reg.jsp</result>
   <result name="login">/log.jsp</result>
</action>

Here, the action node from the struts.xml file states that if an uncaught exception of type SecurityBreachException is thrown by the throwSecurityException method, the Struts 2 framework is required to return a result of login. The login then redirects the user’s browser to return to log.jsp.

You should also take note that action specific mapping takes precedence when the very same exception is mapped globally.

Logging of Exceptions

The Struts 2 framework may be configured for the logging of uncaught exceptions. In order to enable the logging of exceptions that are handled by the Struts 2 framework, there is aneed to specify some parameter values in the struts.xml file. On examining the ExceptionMappingInterceptor class API, you will see that there are three parameter values that need to be set – logEnabled (for enabling logging), logLevel (the log level to be used), and the logCategory (the category for logging), in the message.

So, to set these parameter values for actions dependent on a set of interceptors in package, you need to open the package node and then include following given code in the struts.xml file.

Listing 3. Logging of exceptions

<interceptors>
  <interceptor-stack name="appDefaultStack">
    <interceptor-ref name="defaultStack">
     <param name="exception.logEnabled">true</param>
     <param name="exception.logLevel">ERROR</param>
    </interceptor-ref>
 </interceptor-stack>
</interceptors>
 
<default-interceptor-ref name="appDefaultStack" />

The above interceptors’ node will configure a new stack of interceptors by the name of appDefaultStack. These stacks of interceptors are also based out on defaultStack interceptors.

The ExceptionMappingInterceptor is another interceptor that belongs to the default stack. It is given the name of exception. When you set a param node having the name exception.logEnabled and a value of true, the log parameter of ExceptionMappingInterceptor is set to true.

If the application happens to throw an uncaught exception, the Struts 2 framework handles it, besides also writing an entry to the log that comprises of the stack trace. In the given example, the level to log such exceptions has been set to ERROR.

It is important to note that in the example that we have covered, the logging happens to the Servlet container’s console.

Display Exception Information in Browser

One can also display information about an exception in the browser. This can be done by the use of the s:property tags having the value of exception and exceptionStack.

Listing 4. Displaying information on browser

<h4>The application has a problem.</h4>
 <p>  Feel free to contact tech support and provide the following information:</p> 
 <h4>Exception Name: <s:property value="exception" /> </h4>
<h4>Details: <s:property value="exceptionStack" /></h4>

On the exception interceptor being triggered, it adds to the available fields for display.

Implementation of exception handling in Struts 2

Now that we have taken a look into the various types for exception handling in Java, we shall now learn to do so with a rather simple example.

Listing 5. Struts.xml

<struts>
<package name="default" extends="struts-default">
<global-results>
  <result name="null">/jsp/NullPoint.jsp</result>
  <result name="globalException">/jsp/GlobalExcept.jsp</result>
</global-results>
// In this case, the results are expected to be global results. 
<global-exception-mappings>
  <exception-mapping result="null" exception="java.lang.NullPointerException"/>
  <exception-mapping result="globalException"   exception="java.lang.Exception"/>
</global-exception-mappings>
// An action configuration is adding an addition exception handler.
<action name="Add" class="example.action.Add">
  <exception-mapping result="error" exception="java.lang.NumberFormatException"/>
     <result name="success">/jsp/Success.jsp</result>
     <result name="error">/jsp/Err.jsp</result>
</action>
<action name="Act1" class="example.action.Act1">
     <result name="success">/jsp/Success1.jsp</result>
</action>
<action name="Act2" class="example.action.Act2">
     <result name="success">/jsp/Success1.jsp</result>
</action>
</package>
</struts>

Action Class

We shall implement exception handling in action class here. A NumberFormatException will be thrown if the numbers are not parsed in int.

Listing 6. Add.java

package example.action;
import com.opensymphony.xwork2.Action;
public class Add implements Action 
{
        private String num1, num2;
        private String sum = "";
        public String getNumber1() {
                return num1;
        }
        public String getNumber2() {
                return num2;
        }
        public void setNumber1(String num1) {
                this.num1 = num1;
        }
        public void setNumber2(String num2) {
                this.num2 = num2;
        }
        public String getSum() {
                return sum;
        }
        public void setSum(String sum) {
                this.sum = sum;
        }
        public String execute() throws Exception {
                int numb1 = Integer.parseInt(number1);
                int numb2 = Integer.parseInt(number2);
                int sum = numb1 + numb2;
                setSum("" + sum);
                return SUCCESS;
        }
}

Listing 7. Act1.java

package example.action;
import com.opensymphony.xwork2.Action;
public class Act1 implements Action 
{
        public String execute() throws Exception 
        {
                String string = null;
                System.out.println(string.charAt(7));
                return SUCCESS;
        }
}

This is meant for NullPointerException.

Listing 8. Act2.java

package example.action;
import com.opensymphony.xwork2.Action;
public class Act2 implements Action 
{
        public String execute() throws Exception {
                int num = Integer.parseInt("7b");
                return SUCCESS;
        }
}

This is meant to throw NumberFormatException.

JSP Pages

We shall now develop the JSP pages. There are mainly four pages here.

Listing 9. Index.jsp

<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<s:form action="Addition">
   <s:textfield label="Number 1" name="num1" />
   <s:textfield label="Number 2" name="num2" />
   <s:submit label="Add" />
</s:form>
<hr>
<a href="<s:url action="Act1"/>">ActLink1</a>
<br>
<br> Global Exception         - 
<a href="<s:url action="Act2"/>">ActLink2</a>
<br>
</body>
</html>

Listing 10. Error.jsp

<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h2>An unexpected error has occurred (Exception as per Action page)</h2>
<p>
  <font color="orange">Please get in touch with your system administrator</font>
</p>
<h3>Error</h3>
<br> Exception object transferred to value stack
 <s:property value="[0].top" />
<br>
 <s:property value="%{exception}" />
<hr />
<h3>Stack Trace</h3>
 <s:property value="%{exceptionStack}" />
</body>
</html>

Listing 11. NullPointer.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h2>An unexpected error has occurred (Global - Null Pointer exception)</h2>
<p>
 <font color="blue">Please get in touch with your system administrator</font>
</p>
<h3>Error</h3>
Exception object transferred to value stack
 <s:property value="[0].top" />
<br>
<s:property value="%{exception}" />
</body>
</html>

Listing 12. GlobalException.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Global NumberFormatException</title>
</head>
<body>
<h2>Global NumberFormatException has occurred</h2>
<p>
    <font color="blue">Please get in touch with your system administrator</font>
</p>
<h3>Error Message</h3>
   <br> Exception object transferred to value stack
   <s:property value="[0].top" />
   <br>
   <s:property value="%{exception}" />
</body>
</html>

Once you run the above example, you will get the different messages after exception handling has occurred.

Output will be displayed as below.

Figure 1.Output displayed

Conclusion

The above tutorial should take you through the process involved in the handling of exceptions by making use of the Struts 2 framework. We have learnt about the various interceptors available in Struts 2 and then implemented them with the help of an example.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login