Struts2的异常处理机制

 Struts2的异常处理机制:
任何成熟的MVC框架都应该提供成就的异常处理机制。Strut2也不例外。Struts2提供了一种声明式的异常处理方式。Struts2也是通过配置的拦截器来实现异常处理机制的。
Struts2的异常处理机制通过在struts.xml文件中配置<exception-mapping …>元素完成的,配置该元素时,需要指定两个属性:
exception:此属性指定该异常映射所设置的异常类型。
result:此属性指定Action出现该异常时,系统转入result属性所指向的结果。
1.    异常映射也分为两种:
l 局部异常映射:<exception-mapping…>元素作为<action…>元素的子元素配置。
l 全局异常映射:<exception-mapping…>元素作为<global-exception-mappings>元素的子元素配置。
2.    输出异常信息:
使用Struts2的标签来输出异常信息:
l <s:property value="exception.message"/> : 输出异常对象本身。
l <s:property value="exceptionStack"/> : 输出异常堆栈信息。
3.    示例:
还是修改用户登录示例:
1)       把UserAciton.java中的regist方法改成: 
    public String regist() throws Exception{
        //将用户名,密码添加到数据库中
        //...
        //msg = "注册成功。";
        if(true){
           throw new java.sql.SQLException("没有数据库驱动程序");
       }
       
        return this.SUCCESS;
    }
 

 

2)       修改struts.xml文件:
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="my" extends="struts-default" namespace="/manage">
        <!-- 定义全局处理结果 -->
        <global-results>
        <!-- 逻辑名为sql的结果,映射到/exception.jsp页面 -->
        <result name="sql">/exception.jsp</result>
        </global-results>
       
        <global-exception-mappings>
        <!-- 当Action抛出SQLException异常时,转入名为sql的结果 -->
        <exception-mapping exception="java.sql.SQLException" result="sql"/>
        </global-exception-mappings>
       
        <action name="userOpt" class="org.qiujy.web.struts2.action.UserAction">
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>
 
3)       新增一页面:exception.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
 <head>
    <title>异常信息</title>
 </head>
 
 <body>
 <h2>
 出现异常啦
 </h2>
 <hr/>
   <h3 style="color:red">
   <!-- 获得异常对象 -->
    <s:property value="exception.message"/>
    </h3>
    <br/>
    <!-- 异常堆栈信息 -->
    <s:property value="exceptionStack"/>
</html>
 

猜你喜欢

转载自mystlihai87.iteye.com/blog/1775491