编程知识 cdmana.com

Springboot uses interceptors

Interceptor pair use SpringMvc Is particularly familiar to developers , Because if you want to do a good project, you will use it . Interceptors are very useful in our normal projects , Such as : logging 、 User login status blocking 、 Security interception and so on . and SpringBoot Internally integrated is SpringMVC Control framework , So use it with SpringMVC There is no difference between , It's just a little bit different in configuration . This article only introduces how to use springboot The basic way to use interceptors in .

Environmental Science / Version list :

  • development tool :Intellij IDEA 2020.2.3
  • springboot:2.3.7.RELEASE
  • jdk:1.8.0_211
  • maven: 3.6.3

Project structure

Set up the project

  • pom.xml To configure
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.niu</groupId>
    <artifactId>springboot-interceptor</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>springboot-interceptor</name>
    <description>springboot Interceptors use </description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • Write a controller , Add an interface
package com.niu.springbootinterceptor.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:  controller 
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/22 3:28  Afternoon 
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/22 3:28  Afternoon 
 * @updateRemark:
 * @version: 1.0
 **/
@RestController
public class MyController {


    @GetMapping("test")
    public Object test(){
        System.out.println("test Interface ");
        return "ok";
    }
}
  • Write interceptors
package com.niu.springbootinterceptor.interceptor;

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

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

/**
 * @description:  Interceptor 
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/22 3:26  Afternoon 
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/22 3:26  Afternoon 
 * @updateRemark:
 * @version: 1.0
 **/
public class MyInterceptor  implements HandlerInterceptor {

    /**
     *  Intercept before accessing the interface 
     *  Can make landing judgment 、 Access right judgment 、 Log ...
     *  Method return true Is to allow access to the interface   return false Is access denied 
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(" Ready to access the interface ");
        return true; // Release all interfaces 

    }

    // stay controller Method execution complete execution 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("controller completion of enforcement ");


    }
    // You can catch exceptions here 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(" Page rendering complete , Ready to return to the client ");

    }
}
  • Write configuration classes , Add interceptor
package com.niu.springbootinterceptor.config;

import com.niu.springbootinterceptor.interceptor.MyInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * @description:
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/22 3:26  Afternoon 
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/22 3:26  Afternoon 
 * @updateRemark:
 * @version: 1.0
 **/
@Component
public class WebConfig  implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Add interceptors and set access paths to intercept  * For full match 
       // registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/test");
    }
}
  • The main class
package com.niu.springbootinterceptor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootInterceptorApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootInterceptorApplication.class, args);
    }

}

Start the test

  • Access interface

  • Console printing

The basic use of interceptors is over . But it's very powerful in actual scenarios , Slowly explore in practice

The code has been pushed to github:https://github.com/1603565290m/springboot-interceptor

 

版权声明
本文为[osc_ 706v6usl]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225100106191y.html

Scroll to Top