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

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

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

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

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. <action name="book_*" class="com.stone.action.BookAction" method="{1}">  
  2.             <result name="{1}" type="dispatcher">/WEB-INF/jsp/book_{1}.jsp</result>  
  3.             <result name="error-result">/WEB-INF/jsp/error_result.jsp</result>  
  4.             <exception-mapping result="error-result" exception="java.lang.Exception" />  
  5. </action>  
   先在action中,定义了一个名为“error-result”的result,当前在action中捕获到java.lang.Exception时,映射到"error-result",即跳转到error_result.jsp 

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

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

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. <global-results>  
  2.     <result name="exceptionError" type="dispatcher">/WEB-INF/jsp/error/struts_exception.jsp</result>  
  3. </global-results>  
  4. <global-exception-mappings>  
  5.     <exception-mapping result="exceptionError" exception="java.lang.Exception" />  
  6. </global-exception-mappings>  

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

    

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

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. <default-action-ref name="error" />  
  2. <action name="error">  
  3.     <result>/WEB-INF/struts_errorAction.jsp</result>  
  4. </action>  

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

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

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. <error-page>  
  2.     <error-code>404</error-code>  
  3.     <location>/WEB-INF/404.html</location>  
  4. </error-page>  
   error-code 错误http状态码,location映射到的地址

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

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. <error-page>  
  2.     <!-- 监听到servlet、动态网页中报的相关异常时才会触发 -->  
  3.     <exception-type>java.lang.NullPointerException</exception-type>  
  4.     <location>/WEB-INF/exception.html</location>  
  5. </error-page>  

 

猜你喜欢

转载自tpglzu2015.iteye.com/blog/2204868
今日推荐