1. Define Global exception mapping
In Struts 2, every action definition must be inside a package and that package can extend another; Like :
<package name="home" extends="struts-default-shaan">
This parent package struts-default-shaan may be defined in your struts-default.xml or struts.xml or any other custom struts config XML file.
So, for managing errors, we have define a global exception mapping inside the parent package, so that this mapping will be available to all the actions.
<global-results>
<result name="error">/jsp/common/ErrorHandler.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="com.shaan.ServiceException"
result="error" />
<exception-mapping exception="java.lang.Exception"
result="error" />
</global-exception-mappings>
We have mapped ErrorHandler.jsp with 2 types of exception, so whenever any action (contained in package where we applied this exception mapping) throws these types of exception, it will auto redirect to defined JSP.
2. Define Action
Define Action method which is throwing defined exception
public String display( ) throws ServiceException {
// Business logic here to throw ServiceException,
// without handled by catch
}
3. Define JSP
Use implicit struts2 objects to display exception properties.
/jsp /common/ErrorHandler.jsp
<p>This is a custom error page that displays when an Exception is thrown in any Struts2 component</p>
<s:property value="%{exception.message}" />
<s:property value="%{exceptionStack}" />
You can use any other properties from your custom Exception object to design the error page.
<s:set name="ex" value="%{exception}" scope="request" />
<%
Throwable error = (Throwable) request.getAttribute("ex");
System.out.println("Error :" + error);
System.out.println("Msg :" + error.getMessage());
System.out.println("stack :" + error.getStackTrace());
System.out.println("cause :" + error.getCause());
if(error instanceof ServiceException) {
String title = ((ServiceException) error).getTitle();
String serviceName = ((ServiceException) error).getService();
}
%>
No comments:
Post a Comment
Note: only a member of this blog may post a comment.