Monday, January 10, 2011

Exception handling in Struts

There are two approaches available for the exception handling in struts:

1) Declarative:
Exceptions are defined in the struts-config.xml file and if the exception occurs the control is 
automatically passed to the appropriate error page. The <exception> tag is used to define the 
exception in the struts-config.xml file.

For Example:( If RuntimeException occurs in SaveEmpAaction class, control goes to exception.jsp)

<action path="/saveEmp" type="com.techfaq.SaveEmpAaction" input="/empform.jsp">
<exception key="error.system" type="java.lang.RuntimeException" path="/exception.jsp" />

key:The key defines the key present in file to describe the exception occurred.
type: The class of the exception occurred.
path: The page where the control is to be followed in case exception occurred.
handler: The exception handler which will be called before passing the control to the file specified in path attribute


Defining the Exceptions Globally for the struts-config.xml: (If RuntimeException in any Action class , control goes to exception.jsp)
<exception key="error.system" type="java.lang.RuntimeException" path="/exception.jsp" />

2) Programmatic:
In this approach the exceptions are caught using normal java language try/catch block and instead 
of showing the exception some meaningful messages are displayed.
In this approach the flow of control is also maintained by the programs.
The main drawback of the approach is the developer has to write the code for the flow of the application.

No comments:

Post a Comment