Interceptors and exception handlers

Posted by djmc48 on Wed, 06 Oct 2021 01:31:12 +0200

1. Interceptor

1.1 interceptor configuration

Interceptors in spring MVC are used to intercept the execution of controller methods
Interceptors in spring MVC need to implement HandlerInterceptor

Specific operation

The interceptor of spring MVC must be configured in the configuration file of spring MVC (springMVC.xml):
a. Intercept all paths

		<!--Method 1-->
    <mvc:interceptors>
        <bean class="com.atguigu.mvc.interceptor.FirstInterceptor"></bean>
    </mvc:interceptors>
		<!--Method 2-->
    <mvc:interceptors>
        <ref bean="firstInterceptor"></ref>
    </mvc:interceptors>

b. Exclude specified path

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!--Set that you do not need to be blocked when accessing the home page-->
            <mvc:exclude-mapping path="/"/>
            <ref bean="firstInterceptor"></ref>
        </mvc:interceptor>
    </mvc:interceptors>

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

Interceptors need to implement handlerinterceptors

package com.atguigu.mvc.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Theo
 * @create 2021-09-30 19:07
 */
@Component
class FirstInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("FirstInterceptor-->preHandle");
        return true;
    }

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

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

implement

Interceptors are not executed when accessing the index home page, but only when accessing other pages

When visiting the home page

Visit other pages

1.2 three abstract methods of interceptor

Interceptors in spring MVC have three abstract methods:
1. preHandle: execute preHandle() before the controller method is executed. The return value of boolean type indicates whether to intercept or release. Return true is release, that is, call the controller method; Returning false indicates interception, that is, the controller method is not called

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

3. After compilation: after processing the view and model data, execute after compilation () after rendering the view

1.3 execution sequence of multiple interceptors

1. If each interceptor's preHandle() returns true
At this time, the execution order of multiple interceptors is related to the configuration order of interceptors in the spring MVC configuration file: preHandle() will execute in the configured order, while posthandle() aftercompilation() will execute in the reverse order of configuration

2. If the preHandle() of an interceptor returns false
The preHandle() returns false, and the preHandle() of its previous interceptor will execute. The postHandle() does not execute, and returns false
After compilation() of the interceptor before the interceptor will execute

operation

Interceptor 1

@Component
class FirstInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("FirstInterceptor-->preHandle");
        return true;
    }

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

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

Interceptor 2

@Component
class SecondInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("SecondInterceptor-->preHandle");
        return true;
    }

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

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

Interceptor configuration file

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/"/>
            <ref bean="firstInterceptor"></ref>
        </mvc:interceptor>
    </mvc:interceptors>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/"/>
            <ref bean="secondInterceptor"></ref>
        </mvc:interceptor>
    </mvc:interceptors>

a. If each interceptor's preHandle() returns true
b. If the preHandle() of interceptor 2 returns false

2. Exception handler

2.1 create exception handler based on configuration file

Configure exception handlers in springMVC.xml

    <!--Configure exception handling-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!--
                    properties The key of represents an exception that occurs 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>
        <!--Set the key to share exception information in the request domain-->
        <property name="exceptionAttribute" value="ex"></property>
    </bean>

Create exception page

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
An error occurred
<p th:text="${ex}"></p>
</body>
</html>

Controller method

    @RequestMapping("/testExceptionHandler")
    public String testExceptionHandler(){
        int i = 1/0;
        return "success";
    }

results of enforcement

2.2 creating exception handlers based on annotations

Create ExceptionController control layer method

package com.atguigu.mvc.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author Theo
 * @create 2021-10-05 16:30
 */
//@ControllerAdvice identifies the current class as an exception handling component
@ControllerAdvice
public class ExceptionController {
    //@ExceptionHandler is used to set the exceptions handled by the identified method
    @ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
    public String testException(Exception ex, Model model){
        //ex represents the exception object in the current request processing 
        model.addAttribute("ex",ex);
        return "error";
    }
}

be careful:
1. @ ControllerAdvice: identify the current class as an exception handling component
2. @ ExceptionHandler: used to set the exceptions handled by the identified method

Summary

Come on, the last ten episodes.

Topics: Java Spring mvc