JavaEE SSH框架整合(三) struts2 异常、http错误状态码处理

来源:互联网 发布:网络电话卡有哪些 编辑:程序博客网 时间:2024/05/22 16:01

 struts2的action可能出现访问不到,或action报异常等情况,所以需要作一些处理,给用户一个友好的印象。


1. 异常处理  result声明在action中

<action name="book_*" class="com.stone.action.BookAction" method="{1}"><result name="{1}" type="dispatcher">/WEB-INF/jsp/book_{1}.jsp</result><result name="error-result">/WEB-INF/jsp/error_result.jsp</result><exception-mapping result="error-result" exception="java.lang.Exception" /></action>
   先在action中,定义了一个名为“error-result”的result,当前在action中捕获到java.lang.Exception时,映射到"error-result",即跳转到error_result.jsp 

   注:exception可以是任意一个RuntimeException,可以是自定义的异常。


2. 异常处理 result使用全局result

<global-results>    <result name="exceptionError" type="dispatcher">/WEB-INF/jsp/error/struts_exception.jsp</result></global-results><global-exception-mappings>    <exception-mapping result="exceptionError" exception="java.lang.Exception" /></global-exception-mappings>

    定义一个全局的result,名为exceptionError。全局范围内,捕获到java.lang.Exception时,映射到exceptionError,跳转到对应的jsp。

    

3. 访问地址对应的Action不存在时  使用默认的action

<default-action-ref name="error" /><action name="error">    <result>/WEB-INF/struts_errorAction.jsp</result></action>

   定义默认的action-引用,引用自后面的action-error。  当解析到访问的action不存在时,就调用该默认action。


4. 访问的网页、资源等不存在时 使用web.xml配置

<error-page><error-code>404</error-code><location>/WEB-INF/404.html</location></error-page>
   error-code 错误http状态码,location映射到的地址

5.web.xml也可以处理exception,它处理的是Servlet和动态页面上的异常。

<error-page><!-- 监听到servlet、动态网页中报的相关异常时才会触发 --><exception-type>java.lang.NullPointerException</exception-type><location>/WEB-INF/exception.html</location></error-page>





1 0
原创粉丝点击