我对这些技术不熟悉,我正在使用以下框架来开发应用程序:
- 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/