Method One: Use Simplemappingexceptionresolver to implement exception handling
//Add the following to the spring profile Applicationcontext.xml:<Beanclass= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!--defines the default exception handling page that is used when registering the exception type - < Propertyname= "Defaulterrorview"value= "Error"></ Property> <!--defines the name of the variable that the exception handling page uses to get exception information, by default named Exception - < Propertyname= "Exceptionattribute"value= "Ex"></ Property> <!--defines exceptions that require special handling, with the class name or full pathname as key, and the name of the page as the value - < Propertyname= "Exceptionmappings"> <Props> <propKey= "Cn.basttg.core.exception.BusinessException">Error-business</prop> <propKey= "Cn.basttg.core.exception.ParameterException">Error-parameter</prop> <!--You can also continue to extend the processing of different exception types - </Props> </ Property> </Bean>
Method Two: Implement Handlerexceptionresolver interface Custom exception handler
//1,Add the implementation class Myexceptionhandler for the Handlerexceptionresolver interface, as shown in the following code: Public classMyexceptionhandlerImplementsHandlerexceptionresolver { PublicModelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler, Exception ex) {Map<string, object> model =NewHashmap<string, object>(); Model.put ("Ex", ex); //turn to different pages based on different errors if(exinstanceofbusinessexception) { return NewModelandview ("Error-business", model); }Else if(exinstanceofparameterexception) { return NewModelandview ("Error-parameter", model); } Else { return NewModelandview ("Error", model); } } } //2,Add the following to the spring configuration file Applicationcontext.xml:<bean id= "Exceptionhandler"class= "Cn.basttg.core.exception.MyExceptionHandler"/>
Method Three: Using @exceptionhandler annotations to implement exception handling
//1. Add the Basecontroller class, and declare exception handling in the class using the @exceptionhandler annotation, with the following code: Public classBasecontroller {/**based on @exceptionhandler exception handling*/@ExceptionHandler PublicString exp (httpservletrequest request, Exception ex) {Request.setattribute ("Ex", ex); //turn to different pages based on different errors if(exinstanceofbusinessexception) { return"Error-business"; }Else if(exinstanceofparameterexception) { return"Error-parameter"; } Else { return"Error"; } } } //2. Modify the code so that all controllers that require exception handling inherit the class, as shown below, and the modified TestController class inherits from Basecontroller: Public classTestControllerextendsBasecontroller
Original:http://blog.csdn.net/ufo2910628/article/details/40399539
"Go" Using Spring MVC Unified Exception Handling combat