简体   繁体   中英

Exception Handling in Struts2 with Spring3

I am new to these technologies and I am using the following frameworks to develop an application:

  • Struts 2
  • Spring 3

I am implementing all business logic in Spring so in case any exception has occurred I will show the custom message to the end user.

Could you please explain me how to develop an exception handling functionality in these technologies?

As per my understanding the best approach is to define some predefined Exceptions for your Business layer and throws these Exception back to your Action classes.

S2 provides a number of way to handle those exception and display them to the user, here are few of them

Global Exception Handling

Using the Struts 2 framework you can specify in the struts.xml how the framework should handle uncaught exceptions. The handling logic can apply to all actions (global exception handling) or to a specific action. Let's first discuss how to enable global exception handling.

 <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>

Even if you want a fine level control you are free to configure exception handling at per Action basis

 <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>

Its your preference, how you want to configure them.For details refer to the doc

You have even the option to access Exception details from Value-Stack.By default, the ExceptionMappingInterceptor adds the following values to the Value Stack:

  • exception The exception object itself
  • exceptionStack The value from the stack trace

and here is the way to access those object in JSP

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

For details refer to the details

You can pick those

Struts 2

Spring 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM