SpringMVC interceptor and exception handling

catalogue

1, Interceptor configuration

2, Execution sequence of multiple interceptors

3, Exception handling based on configuration file

4, Annotation based exception handling

1, Interceptor configuration

1. Interceptors in springmvc are used to intercept the execution of controller methods

2. Interceptors in springmvc need to implement the HandlerInterceptor interface

3. The interceptor of SpringMVC must be configured in the configuration file of SpringMVC:

<mvc:interceptors>
        <ref bean="firstInterceptor"/>
        <bean class="mvc.controller.secondInterceptor"/>  
<!-- The above two configurations are correct DispatcherServlet Intercept all requests processed -->
</mvc:interceptors>
 <mvc:interceptors>
      <mvc:interceptor>
          <mvc:mapping path="/**"/>
          <mvc:exclude-mapping path="/testRequestEntity"/>
          <ref bean="firstInterceptor"/>
      </mvc:interceptor>
</mvc:interceptors>

<!--
The above configuration methods can be ref or bean Tag setting interceptor,
adopt mvc:mapping Set the request to be intercepted,/**Indicates that all requests are blocked
 adopt mvc:exclude-mapping Set the requests that need to be excluded, that is, the requests that do not need to be intercepted
-->

Interceptors in SpringMVC have three abstract methods:

preHandle: execute preHandle() before the controller method is executed. The return value of its boolean type indicates whether to intercept or release. Return true to release, that is, call the controller method; Returning false indicates interception, that is, the controller method is not called

postHandle: execute postHandle() after the controller method is executed

Aftercompilation: after processing the view and model data, execute aftercompilation() after rendering the view

Implementation of interceptor method:

@Component
public class firstInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("firstInterceptor"+"<->"+"preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("firstInterceptor"+"<->"+"postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("firstInterceptor"+"<->"+"afterCompletion");
    }

}

2, Execution sequence of multiple interceptors

1. If the preHandle() of each interceptor returns true

At this time, the execution order of multiple interceptors is related to the configuration order of interceptors in SpringMVC configuration file:

preHandle() will be executed in the order of configuration, while postHandle() and aftercompilation() will be executed in the reverse order of configuration

For example, we configured two interceptors, firstInterceptor and secondInterceptor. The execution sequence is as follows:

firstInterceptor<->preHandle
secondInterceptor<->preHandle


secondInterceptor<->postHandle
firstInterceptor<->postHandle


secondInterceptor<->afterCompletion
firstInterceptor<->afterCompletion

2. If preHandle() of an interceptor returns false

Then the preHandle() returning false and the preHandle() of the interceptor before it will be executed,

postHandle() is not executed,

After compilation() of the interceptor before the interceptor that returns false will be executed

Suppose there are five interceptors: 1, 2, 3, 4, 5. If the preHandle of 3 returns false, the preHandle of 1, 2, and 3 will be executed, the postHandle() of all interceptors will not be executed, and the aftercompilation of 1 and 2 will be executed.

3, Exception handling based on configuration file

SpringMVC provides an interface to handle exceptions during the execution of controller methods:

                HandlerExceptionResolver

The implementation classes of the HandlerExceptionResolver interface are:

DefaultHandlerExceptionResolver and SimpleMappingExceptionResolver

SpringMVC provides a custom exception handler SimpleMappingExceptionResolver, which can be used in the following ways:

<bean
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!--
            properties The key of represents an exception during the execution of the processor method
            properties The value of indicates that if a specified exception occurs, set a new view name and jump to the specified page
            -->
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
    <!--
    exceptionAttribute Property set a property name to share the exception information in the request domain
    -->
    <property name="exceptionAttribute" value="eMsg"></property>
</bean>

Test the controller method of exception handling:

 @RequestMapping("/testException")
    public String testException(){
        Integer num=1/0;
        return "success";
    }

Link to test exception handling:

<a th:href="@{/testException}">Test exception handling</a><br/>

error page:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Error </title>
</head>
<body>
    <div th:text="${eMsg}"></div>
</body>
</html>

4, Annotation based exception handling

@ControllerAdvice
public class ExceptionHandler {
    @ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})
    public String testException(Exception e, Model model){
        model.addAttribute("eMsg",e);
        return "error";
    }
}

In this way, the configuration file can be replaced. When an error occurs, jump to the error page and display the exception information.

Tags: Spring servlet Spring MVC mvc

Posted by darksystem on Fri, 05 Aug 2022 21:42:54 +0300