7. Exception Handling with Struts
An exception handler allows you to declaratively handle an exception in the struts-config.xml file by associating an exception to a user friendly message and a user friendly JSP page that will display if the exception occurs.
Struts-config.xml
<action path="/userRegistration"
type="strutsTutorial.UserRegistrationAction"
name="userRegistrationForm"
input="/userRegistration.jsp">
<exception type="java.sql.SQLException"
key="userRegistration.sql.exception"
path="/userRegistrationException.jsp" />
<forward name="success" path="/regSuccess.jsp" />
<forward name="failure" path="/regFailure.jsp" />
</action>
Notice the use of <html:errors> to display the error message associated with the exception in JSP display.
SUMMARY
总的来说,sturts的配置文件[struts-config.xml,位于WEB-INF目录下]很重要。
<action-mappings>
<action path="/userRegistration"
type="strutsTutorial.UserRegistrationAction"
name="userRegistrationForm"
input="/jsp/userRegistration.jsp"
validate="true"
cancellable="true"
attribute="user">
l Path: 用户request的servlet
l Type: 该请求所映射的action处理类
l Name: 如果是input view, request表单所映射的ActionForm
l Validate: 若为true,是否调用ActionForm的validate()方法,缺省为true
l Cancelable: 表示request表单中的<html:cancel />能否被点击,缺省为false
l Attribute: maps the ActionForm into a scope (session by default) under "user", 也就是说attribute会把formbean储存在一个叫做"user"的对象里, 而JSP页面可通过<bean:write name="user" property="firstName" /> 显示该对象里的内容
<exception type="java.sql.SQLException"
key="userRegistration.sql.exception" path="/jsp/userRegistrationException.jsp" />
l Type: 异常类型
l Key: 异常信息的键,用来获得显示给用户的error message
l Path: 重定向到的页面
<forward name="success" path="/jsp/regSuccess.jsp" />
l 由Action类返回的ActionFoward对象以及对应的jsp文件
</action-mappings>