java - Struts2 和 Spring3 中的异常处理

标签 java spring struts2

我对这些技术不熟悉,我正在使用以下框架来开发应用程序:

  • Struts 2
  • Spring 3

我正在 Spring 中实现所有业务逻辑,因此如果发生任何异常,我将向最终用户显示自定义消息。

您能否解释一下如何使用这些技术开发异常处理功能?

最佳答案

根据我的理解,最好的方法是为您的业务层定义一些预定义的异常,并将这些异常抛出回您的操作类。

S2 提供了多种方法来处理这些异常并将其显示给用户,以下是其中的一些

全局异常处理

使用 Struts 2 框架,您可以在 struts.xml 中指定框架应如何处理未捕获的异常。处理逻辑可以应用于所有操作(全局异常处理)或特定操作。我们首先讨论如何启用全局异常处理。

 <global-exception-mappings>
    <exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" result="securityerror" />
     <exception-mapping exception="java.lang.Exception" result="error" />
   </global-exception-mappings>

  <global-results>
        <result name="securityerror">/securityerror.jsp</result>
    <result name="error">/error.jsp</result>
   </global-results>

即使您想要精细的级别控制,您也可以根据每个操作自由配置异常处理

 <action name="actionspecificexception" class="org.apache.struts.register.action.Register" method="throwSecurityException">
     <exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" 
          result="login" />
      <result>/register.jsp</result>
      <result name="login">/login.jsp</result>
   </action>

这是您的偏好,您想如何配置它们。有关详细信息,请参阅文档

您甚至可以选择从 Value-Stack 访问异常详细信息。默认情况下,ExceptionMappingInterceptor 将以下值添加到 Value Stack:

  • 异常异常对象本身
  • ExceptionStack 堆栈跟踪中的值

这是在 JSP 中访问这些对象的方法

 <s:property value="%{exception.message}"/>
 <s:property value="%{exceptionStack}"/>

详情请参阅详情

关于java - Struts2 和 Spring3 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10169499/

相关文章:

java - 如何为我的 "home screen"Android studio 设置临时片段

java - 如何从 JAVA 与 SAP 应用程序通信

java - 为什么我的 GUI 在 SwingWorker 线程运行时没有响应?

java - @RequestParam 为空(Spring MVC)

java - 如何转换 struts2 中不是 SHORT 格式的日期?

java - 为什么spring security无法获取用户名?

java - 如何从父方法获取注解?

java - 通过Interceptor或HttpEntity向RestTemplate添加http header ?

spring - Struts2;为 StrutsSpringTestCase JUnit 测试保持 session 打开

Struts2 ActionContext 和 ValueStack?