Eclipse or SUNrise...

Eclipse or SUNrise...
...JAVA for sure

Tuesday, August 26, 2008

Exception Handlers in Struts

Although Struts version 1.x.x is 8 years old, it still is a solid ground for web applications. One of the key features of the version 1 of Struts is the ExceptionHandler capabilities. This functionality allows developers to trace exceptions produced in the web tier. It is very important because errors in jsp pages or servlets are hard to pinpoint. The ExceptionHandler is a simple servlet, just like another action classes - it is a perfect place to log error information which will be in many situations invaluable.

To use it we have to do only 2 things, first we should make our own ExceptionHandler class. Here is an example code:



public class MyOwnExceptionHandler extends
org.apache.struts.action.ExceptionHandler {

public ActionForward execute(Exception ex, ExceptionConfig ae,
ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response)
throws ServletException {

System.err.println("==> MyOwnExceptionHandler\nexception: " + ex.toString()
+ " \nmapping: " + mapping.toString());

// TODO here log the info

ActionForward forward = super.execute(ex, ae, mapping, formInstance,
request, response);

return (forward);
}
}


Than edit the struts-config.xml and in <global-exceptions> tag paste these lines:


<exception handler="pl.sample.hellostruts.handlers.MyOwnExceptionHandler"
key="global.error.message" path="/exceptionPage.jsp" scope="request"
type="java.lang.Exception"></exception>


handler properies shows struts the exception handler class, path is the default page where the user will be directed after the fault (we can direct him dinamically in the MyOwnExceptionHandler class as well). The type defines a kind of exception on which the handler class will be initialized - in this example the MyOwnExceptionHandler will run when a java.lang.Exception will accur and which will not be catched in the code.