设计模式:责任链
在struts中支持声明式的异常处理,指的是说action中如果出现异常了尽管往外抛,到最后我会给你一个统一的接口,然后让你在特定页面进行处理。
1.编写Action
package com.sxt.action; import java.sql.SQLException; import com.opensymphony.xwork2.ActionSupport; import com.sxt.model.User; public class UserAction extends ActionSupport{ private User user; public String login() throws SQLException{ /*因为我们使用了声明式的异常处理,所以在这里我们就不需要使用try-catch了,让action中的异常往外抛,使用 * struts的声明式的异常管理可以捕捉到该异常并进行相应的处理 */ user.setName("");//设置name为空字符串 if("".equals(user.getName())){ throw new SQLException(); } return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
2.配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.devMode" value="true"></constant> <package name="common" extends="struts-default"> <!--全局性result--> <global-results> <result name="global_error">/global_error.jsp</result> </global-results> <!--全局性的异常映射,该异常映射针对所有的Action--> <global-exception-mappings> <!--该result会先到对应的action配置下面对找,如果没找到,才会使用全局性result--> <exception-mapping result="global_error" exception="java.lang.Exception"></exception-mapping> </global-exception-mappings> </package> <package name="admin" namespace="/admin" extends="common" ><!--注意:继承了common--> <action name="userAction" class="com.bjsxt.action.UserAction" method="login"> <result>/admin/success.jsp</result> <result name="input">/admin/input.jsp</result> <!--局部性的: 异常映射,当该Action中一旦发生SQLException异常,会跳转到result指定的界面(在这里是error.jsp页面)。 该异常映射只针对该Action。 <exception-mapping result="error" exception="java.sql.SQLException" /> <result name="error">/error.jsp</result> --> </action> </package> </struts>
说明:一旦userAction抛出了异常,它就会在自己的包中找有没有配置异常映射,如果没有就会到父类的包中去找,在这里是common package,在common package中配置了全局性的异常映射和全局性的result