08 struts.xml之异常处理

1.   修改JAVA

  public class UserAction extends ActionSupport

{

        private String userName;

   

       public String add()

            throws Exception

        {

            if (userName == null)

            {

                System.out.println("RuntimeException");

                throw new RuntimeException("RuntimeException");

           }

            return SUCCESS;

}

public String getUserName()

{

return userName;

 }

 

public void setUserName(String userName)

{

    this.userName = userName;

}

 }

2.   修改struts.xml

<package name="struts"namespace="/struts" extends="struts-default">

        <default-action-ref name="user_add"></default-action-ref>

        <global-results>

           <result name="struts">/Adminadd_success.jsp</result>

           <result name="error">/error.jsp</result>

        </global-results>

       

        <global-exception-mappings>

<exception-mapping result="error"exception="java.lang.Exception"></exception-mapping>

       </global-exception-mappings>

 

<action name="user*"class="action.UserAction" method="{1}">

            <result>/user{1}_success.jsp</result>

        </action>

       ……

</package>

3.   添加页面error.jsp

 <body>

            This is My Error. <br>

  </body>

4.   运行

启动tomcat

1)        访问: http://localhost:2000/Gao_struts2/struts/useradd.action

2)        页面显示:This is My Error.

3)  访问http://localhost:2000/Gao_struts2/user1/user_struts.action

页面显示:

user add success! 
aaa

a
userDao
addUser
8

 

5.   总结

1)        执行UserAction类的add()方法抛出的异常,通过在struts.xml中配置统一异常处理global-exception-mappings返回exception-mapping 中的error

2)        global-results中配置error对应的/error.jsp,所以最后页面显示This is My Error.

3)        global-exception-mappings中也可以指定明确的异常如SQLException等。

4)        global-results需配置在global-exception-mappings前面,否则初始化会失败。

5)        global-exception-mappings也可以配置在action里面

<action name="user*" class="action.UserAction"method="{1}">

            <result>/user{1}_success.jsp</result>

             <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>

              <result name="error">/error.jsp</result>

    </action>

6)        global-exception-mappings主要用于对action层操作出现的数据库异常,参数异常等进行同一的页面提示处理

7)        global-exception-mappings原理:通过拦截器技术即AOP技术对add方法加了异常处理:

 try

            {

                add();

            }

            catch (Exception e)

            {

                return "error";

}

8)  祝福雅安!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值