Java ProgrammingLearn How To Handle Exceptions In A Struts 2 Application

Learn How To Handle Exceptions In A Struts 2 Application

Learn-How-to-handle-exceptions-in-a-Struts-2-application_KaushikPal-740X296
Exceptions are a part of all types of processing both in software and hardware applications. Though most of the exceptions are identified and addressed there may be exceptions that are unidentified and not interpreted. Struts 2 Application provides effective ways to identify, interpret and address such exceptions. The good thing about exception handling with Struts 2 is the capabilities to handle exceptions are embedded within the framework and there is no need for additional configuration. Struts 2 derives a lot of its capabilities from the Model View Controller (MVC) framework and has unique architectural features both of which provides clear ways to identify and address exceptions. The architecture of Struts 2 is modular and each module or component has specific ways to interact with other modules. Exceptions during such interactions can be identified and addressed.

In this article, we will explore a little bit about Struts 2 framework and then concentrate on the exception handling part. We will also check one sample application for the implementation purpose.

Struts 2 and MVC Framework
While the Struts 2 framework is to an extent based on the MVC framework, there are certain unique components in the Struts 2 framework. Let us view the commonalities and differences between the two frameworks.

Commonalities

  • Both Struts and MVC frameworks have components that have clearly defined roles and responsibilities. For example, in MVC, the components Model, View and Controller manage data business logic, showing the data and other stuff in the user interface as requested by the user and acting as interface between the Model and Viewer components respectively. Similarly, in Struts 2, there are multiple such components such as Controller, Actions and Interceptor that perform their responsibilities in a certain, predefined way.
  • Both Struts 2 and MVC framework are ideal for developing web-based applications. Both makes web development easier.

Differences
The main difference is Struts 2 started off in the form of Struts 1 by inheriting the framework from MVC and went on to carve out a massively improved version in Struts 2. The MVC provides the foundation and Struts 2 has added certain enhancements such as tag support and POJO forms.

What are the features?
The main features of Struts 2 are described below:

    • Plain Old Java Object (POJO) forms and POJO actions

To receive form inputs provided by a user through a web-based user interface, Struts 2 uses POJO forms and to take actions based on the inputs, Struts 2 uses POJO actions.

    • Tag support

Struts2 has improved the form tags to the extent that it saves a lot of effort from developers in writing code to develop forms.

    • AJAX support

Struts2 enables developers to use the capabilities of AJAX for developing faster and interactive web applications.

    • Easy integration

Struts2 allows easy integration with other frameworks such as spring, Tiles and SiteMesh.

    • Easy to modify tags

Developers can easily modify the tags in Struts 2 with the use of the Freemarker templates.

    • Less configuration

A lot of features come configured by default so that developers or administrators do not have to spend time and effort in configuration.

    • Comprehensive exception handling

Struts2 enables developers identify hitherto unidentified exceptions and generate notifications for users. Exceptions can be managed both locally and globally with available default configurations.

Brief architecture – Struts 2
As stated earlier, Struts 2 has a well-defined, definitive architecture that specifies the responsibilities of each component within the architecture. Exceptions can happen at any of these levels and they can be addressed. Given below is a description of the cycle of activities performed by all components in the framework.

  1. The user sends a request for a resource through a web-based interface. The requested resource could be a page.
  2. The request is reviewed by the FilterDispatcher component and an appropriate Action, another component, is selected.
  3. Interceptors applies validation logic.
  4. The selected Action performs the requested operation.
  5. Interceptors perform post processing after the operations by the Actions are completed, if required.
  6. This is an optional step. If there is an exception, the exception interceptor processes it.
  7. The results or the resources are sent to the user through the View model.

Exception handling in Struts 2 – General Guidelines
With Struts 2, exception handling is easier and comprehensive. Exception handling capabilities come configured by default and there is no need to do anything additional. The exception interceptor is configured to identify exceptions and redirect users to corresponding error pages. Given below are some of the exception handling capabilities of Struts 2:

  • Struts offers exception handling through its com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor interceptor which is pre-packaged.
  • Exceptions can be handled both locally and locally.
  • Local handling means defining specific error pages for specific exceptions so that users are redirected to the error pages when the exception occurs.
  • In the case of global handling, a global exception can be set which will apply to all actions. For example, to identify all NullPointerException exceptions of the same type, the <global-exception-mappings…> tag inside <package…> tag could be added.

Configuration
The steps to configure Struts 2 are given below. It is assumed you already have JDK (5+), Tomcat and Eclipse installed in the machine.
Set up the Java Development Kit (JDK)

  1. Download the latest JDK from Oracle’s website.
  2. Set PATH and JAVA_HOME environment variables to refer to the directory that has javac and java.

Setup Apache Tomcat

  1. Download the latest version of Tomcat from http://tomcat.apache.org/.
  2. Unpack the binary distribution to a local disk and create the CATALINA_HOME environment variable that points to these locations.
  3. Execute the Tomcat by double-clicking the startup.bat exe file.

Setup Struts 2 Libraries

  1. Download the latest version of Struts 2 from http://struts.apache.org/download.cgi.
  2. Extract the zip file to the local disk and set the CLASSPATH variable properly.

Note: You could download the latest versions of the software on any OS and then use the Eclipse IDE for your convenience.

Sample exception handling application
Struts have a very efficient mechanism for handling exceptions. It provides an interceptor called ‘exception’, which manages all the tasks. In this example we will write code for all the components and error pages to handle some simple exceptions. Error pages are an important part of struts exception handling, as developers can make any number of error pages and redirect as per requirement.

Let us check different components one by one. We will create three jsp files for landing page, success and error condition. We will also have one action class and struts.xml configuration file.

This is the index page for taking input from the users. It will forward the request to the action class.

Listing 1: This is the landing page (index. 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>Struts Excp Demo</title>
</head>
<body>
   <h1>This is Struts exception example</h1>
   <form action="strutsexpdemo">
      <label for="empname">Employee name please:</label><br/>
                  <label for="emprole">Employee role please:</label><br/>
      <input type="text" name="empname"/>
                  <input type="text" name="emprole"/>
      <input type="submit" value="Submit"/>
   </form>
</body>
</html>

Following is the success page to be displayed once the input is processed properly by the action class. If there is any exception, then it will redirect to some other pages as configured in the struts.xml file.

Listing 2: This is the success page (StrutsExcpDemo.jsp)

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts Excp Demo - This is success page</title>
</head>
<body>
   Welcome to Struts Exception Demo <s:property value="empname"/>
   <s:property value="emprole"/>
</body>
</html>

Following is the custom error page and it will be displayed when any exception occurs in the processing. In our case it will be redirected to this page due to null pointer exception.

Listing 3: This is the custom error page (errorpage.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>Struts Excp Demo - This is error page</title>
</head>
<body>
   This is custom error page - Display error messages here
</body>
</html>

This is the main action class which does the actual processing of all requests from the front end. The execute() method is called for processing. And success or error is returned as per the condition. In our case it will throw an exception.

Listing 4: This is the action class (StrutsExcpDemoAction.java)

package com.eduonix.strutsexcpdemo;
// This is for supporting common constants like success, error, none etc
import com.opensymphony.xwork2.ActionSupport;
public class StrutsExcpDemoAction extends ActionSupport{
   private String empname;
   private String emprole;
   public String execute(){
                  String ename = null;
                  String erole = null;
                  // Creating forced exception
                  ename = ename.substring(0);
                  erole = erole.substring(1);
      return SUCCESS;
   }  
   public String getEmpname() {
      return empname;
   }
   public void setEmpname(String empname) {
      this.empname = empname;
   }
   public String getEmprole() {
      return emprole;
   }
   public void setEmprole(String emprole) {
      this.emprole = emprole;
   }
}

This is the configuration file where all mappings are defined. For success it is redirected to the success page and for error it is redirected to an error page. This is the controller for the entire application.

Listing 5: This is the configuration 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.devMode" value="true" />
   <package name="strutsexpdemo" extends="struts-default">    
      <action name="strutsexpdemo"
         class="com.eduonix.strutsexcpdemo.StrutsExcpDemoAction"
         method="execute">
        <exception-mapping exception="java.lang.NullPointerException"
         result="error" />
         <result name="success">/StrutsExcpDemo.jsp</result>
                <result name="error">/errorpage.jsp</result>
      </action>
   </package>
</struts>

Now we have created all the components. So now we need to make a WAR file and deploy it in tomcat web server. After successful deployment, open the following link in browser and you will get the index page.
http://localhost:8080/StrutsExcpDemo/index.jsp
Now, enter any data and click on the ‘Submit’ button. It will be redirected to the error page and the following message will be displayed.

Output: This is custom error page – Display error messages here
custom error page
Image1: Output error page

Conclusion
Struts2 makes exception handling easy because of local and global settings. The global handling of exception types can save a lot of time and effort and it contributes to good user experience. In this tutorial we have discussed all the aspects of Struts exception framework and how it handles exception. The sample application is also a complete program to learn and implement it in practical and real life projects.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -