|
The struts not only introduced the exception handling mechanism and pass the flow to the appropriate page automatically, it also gives the flexibility to the programmers to create their own Exception Handlers. The struts provides org.apache.struts.action.ExceptionHandler class for creating the custom exception handlers. All the custom Exception Handlers should extend the ExceptionHandler class and override the execute() method.
The below example will demonstrate custom ExceptionHandler for the user program.
Note:- The below example will transfer the control to the index.jsp after calling the exception handler. In the struts-config.xml we are adding the global exception for RuntimeException. You can add any exception like the previous example to some actions only. The code for adding it as follows :-
<exception key="error.system" type="java.lang.RuntimeException" handler="com.visualbuilder.handler.CustomExceptionHandler" path="/index.jsp" />
Example For ExceptionHandler :-
(1) Creating the Exception Handler Class
package com.visualbuilder.handler;
import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ExceptionHandler; import org.apache.struts.config.ExceptionConfig;
public class CustomExceptionHandler extends ExceptionHandler {
public ActionForward execute(Exception exception, ExceptionConfig config, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException {
try { // TODO CustomeCode System.out.println("Exception Handler for the specific error"); }catch (Exception e) {
} return (super.execute(exception, config, mapping, formInstance, request, response)); } }
(2) Struts-config.xml file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <!-- ================================================ Form Bean Definitions --> <form-beans>
</form-beans> <!-- ========================================= Global Exception Definitions --> <global-exceptions>
<exception key="error.system" type="java.lang.RuntimeException" handler="com.visualbuilder.handler.CustomExceptionHandler" path="/index.jsp" />
</global-exceptions> <!-- =========================================== Global Forward Definitions --> <global-forwards></global-forwards> <!-- =========================================== Action Mapping Definitions --> <action-mappings>
<action path="/exception" type="com.visualbuilder.ExampleAction" input="/index.jsp" /> </action-mappings> <!-- ======================================== Message Resources Definitions --> <message-resources parameter="MessageResources" /> </struts-config> |