Java SpringMVC Exception Handling SimpleMappingExceptionResolver Class Detailed Explanation

  • 2021-11-13 01:36:19
  • OfStack

Spring 3.0 handles exceptions in two ways:

One is to use the HandlerExceptionResolver interface, and Spring already provides the default implementation class SimpleMappingExceptionResolver.

The second method is implemented inside Controller, which is more flexible.

Judging from the current survey results, these two methods cannot coexist. We generally use the first method in the project.

The following two usage modes are described respectively under 1:

1. Mode based on HandlerExceptionResolver interface

In this way, only the resolveException method needs to be implemented, which returns an ModelAndView object, judges the exception type inside the method, and then returns the appropriate ModelAndView object. If the method returns null, Spring will continue to look for other Bean that implements HandlerExceptionResolver interface. In other words, Spring searches all Bean registered in its environment that implement the HandlerExceptionResolver interface, one by one, until one ModelAndView object is returned.


public class CustomExceptionHandler implements HandlerExceptionResolver {  
  
    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object object, Exception exception) {  
        if(exception instanceof IOException){  
            return new ModelAndView("ioexp");  
        }else if(exception instanceof SQLException){  
            return new ModelAndView("sqlexp");  
        }  
        return null;  
    }  
}

This class must be declared in the Spring configuration file, or the @ Component tag is used for Spring to manage it. At the same time, Spring also provides the default implementation class SimpleMappingExceptionResolver, which only needs to be declared by injecting into Spring configuration file. Custom implementation class and default implementation class can be used at the same time.

Examples are as follows:


<!--  Custom implementation class  --><bean id="exceptionHandler" class="com.enh.test.CustomExceptionHandler"/><!--  Default implementation class injection  --><bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
    <!--  Define default exception handling pages for all exceptions, exceptionMappings Undefined exceptions use this default configuration  -->  
    <property name="defaultErrorView" value="error"></property>  
    <!--  Defines the name of the variable used by the exception handling page to get exception information. The default name is exception -->  
    <property name="exceptionAttribute" value="ex"></property>  
    <!--  Define exceptions that require special handling, using class names or full pathnames as key The exception page file name is used as a value to map different exceptions to different pages.     -->  
    <property name="exceptionMappings">  
        <props>  
            <prop key="IOException">error/ioexp</prop>  
            <prop key="java.sql.SQLException">error/sqlexp</prop>  
        </props>  
    </property>  
</bean>

A typical exception display interface is as follows:


<html> 
<head><title>Exception!</title></head> 
<body> 
    <% Exception ex = (Exception)request.getAttribute("exception"); %> 
    <H2>Exception: <%= ex.getMessage();%></H2> 
    <P/> 
    <% ex.printStackTrace(new java.io.PrintWriter(out)); %> 
</body> 
</html>

exception is in SimpleMappingExceptionResolver is stored in request, specific can see the source code.

In addition, the exception display interface configured here only includes the main file name, and the file path and suffix have been specified in viewResolver. If the page cannot be found, the page path will be adjusted according to the error prompt.

2. Internal separate implementation of Controller

This method needs to be defined in Controller, and then a method is created and modified with @ ExceptionHandler annotation to handle exceptions. This method is basically similar to the method modified with @ RequestMapping, except that one more parameter of type Exception can be added, and one or more exception types can be added in @ ExceptionHandler. If it is empty, it is considered that all exception type errors can be triggered.


@Controller  
public class ExceptionHandlerController {  
      
    @ExceptionHandler(value={IOException.class,SQLException.class})  
    public String exp(Exception ex,HttpServletRequest request) {  
        request.setAttribute("ex", ex);  
        return "/error.jsp";  
    }  
  
}

3. Related issues

Is there a conflict between error-page configured in HandlerExceptionResolver and web. xml?

Configuring error-page in web. xml is also the page displayed when a configuration error occurs:


<error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
</error-page>

If resolveException returns ModelAndView, it will be displayed according to the page in the return value first. However, resolveException can return null, which shows the 500 status code configuration page of error-page in web. xml.

Explanation of the return value in the API documentation:


return a corresponding ModelAndView to forward to, or null for default processing.

Related articles: