您的位置:首页 > 编程语言 > Java开发

Struts 1 学习笔记-5-3(Struts的自动处理异常以及模式套用)

2008-02-16 18:44 691 查看
一.自动处理Exception:

1.首先要确保在代码里没有捕获异常,而是将异常全部抛给上层。

2.在struts-config.xml中配置,例(你也可以不配置path,而是在要显示的界面上通过<html:errors/>调用,当然不要忘记引入标签<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>  ):

exception可以配置成全局的或者专为单个action,按需要配置


<exception path="/error.jsp" key="drp.user.not.found" type="com.codedestiny.struts.UserNotFoundException"></exception>


<exception path="/error.jsp" key="dpr.user.password.error" type="com.codedestiny.struts.PasswordErrorException"></exception>

3.error.jsp(就是通过标签调用):




<%...@ page language="java" import="java.util.*" pageEncoding="GB18030"%>




<%...@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>  


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>


  <head>


  </head>


  


  <body>


    <h1><html:errors/></h1>


  </body>


</html>



二.模式套用:

1.使用Struts的DispatchAction在转向时可以采用模式套用的方式,先上一个简易的UserAction.java:


package com.bjsxt.drp.web.usermgr.actions;




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.actions.DispatchAction;






public class UserAction extends DispatchAction ...{


    




    public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ...{


        return mapping.findForward("success");


    }


    




    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ...{


        return mapping.findForward("success");


    }


    




    public ActionForward find(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ...{


        return mapping.findForward("success");


    }


    




    public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ...{


        return mapping.findForward("success");


    }


    




    public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ...{


        return mapping.findForward("success");


    }


}



 

2.在struts-config,xml中作如下配置:


<action path="/user/*" type="com.bjsxt.drp.web.usermgr.actions.UserAction" scope="request" parameter="command">


         <forward name="success" path="/user/{1}_success.jsp"></forward>


</action>

 

3.这样一来如果这样一个链接user/add.do?command=add即可访问到user/add_success.jsp

   user/delete.do?command=delete可访问到user/delete_success.jsp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息