Struts声明式异常
1.编写相应的异常类;
2.捕捉相应的异常类,进行抛出,可以把该代码封装到相应的方法中,比如在LoginDAO这个类中,有个isLogin()方法判断是否登陆成功,同时根据需要抛出相应异常,如:UserNotFoundException、PasswordErrorException等。在LoginAction这个Action类中调用LoginDAO类中的isLogin()方面验证用户是否登陆成功;
3.在国际化资源文件中,编写相应异常的key,以及对于的value值;
4.在struts-config.xml中配置以上相关需要的信息,同时,配置<exception/>标签,指定相应的key,type的属性,key值对应国际化资源文件中异常的key值,type为自己编写的异常类。同时,在相应Action中配置input属性,该属性为出现异常时进行跳转的页面。如在<exception/>中配置path属性,则path属性优先于<action/>中的input属性。
5.在需要显示错误提示的jsp页面用<html:errors/>标签进行错误信息读取。
LoginDAO类:
public class LoginDAO {
public void isLogin(String username,String password){
if(!(username.equals("admin"))){
throw new UserNotFoundException();
//事先声明的异常类
}
else if(!(password.equals("admin"))){
throw new PasswordErrorException()
;//事先声明的异常类
}
}
}
LoginAction类:
package wiki.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm daf = (DynaActionForm)form;
String username = (String)daf.get("username");
String password = (String)daf.get("password");
LoginDAO loginDAO = new LoginDAO();
loginDAO.isLogin(username, password);
return mapping.findForward("success");
}
}
struts-config.xml中的部分配置
<action-mappings> <action path="/login" type="wiki.struts.LoginAction" name="loginForm" scope="request" input="/login.jsp" > <exception key="login.user.name.error" type="wiki.struts.UserNotFoundException" path="/login_error.jsp" /> <exception key="login.user.password.error" type="wiki.struts.PasswordErrorException" path="/login_error.jsp" /> <forward name="success" path="/login_success.jsp" /> </action>