SpringBoot使用拦截器

拦截器对使用SpringMvc的开发人员来说特别熟悉,因为你只要想去做好一个项目必然会用到它。拦截器在我们平时的项目中用处有很多,如:日志记录、用户登录状态拦截、安全拦截等等。而SpringBoot内部集成的是SpringMVC控制框架,所以使用起来跟SpringMVC没有区别,只是在配置上有点不同。本文只介绍如何在springboot中使用拦截器的基本方式。

环境/版本一览:

  • 开发工具:Intellij IDEA 2020.2.3
  • springboot:2.3.7.RELEASE
  • jdk:1.8.0_211
  • maven: 3.6.3

项目结构

搭建项目

  • pom.xml配置
<?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拦截器使用</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>
  • 写一个控制器,加入一个接口
package com.niu.springbootinterceptor.controller;

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

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


    @GetMapping("test")
    public Object test(){
        System.out.println("test接口");
        return "ok";
    }
}
  • 编写拦截器
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: 拦截器
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/22 3:26 下午
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/22 3:26 下午
 * @updateRemark:
 * @version: 1.0
 **/
public class MyInterceptor  implements HandlerInterceptor {

    /**
     * 访问接口之前拦截
     * 可以做登陆判断、访问权限判断、记录日志。。。
     * 方法return true是允许访问接口  return false是拒绝访问
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("准备访问接口");
        return true; //放行所有接口

    }

    //在controller方法执行完毕执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("controller执行完毕");


    }
    //可以在这里捕捉异常
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("页面渲染完成,准备返回给客户端");

    }
}
  • 编写配置类,加入拦截器
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 下午
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/22 3:26 下午
 * @updateRemark:
 * @version: 1.0
 **/
@Component
public class WebConfig  implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器并设置拦截的访问路径 *代表全匹配
       // registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/test");
    }
}
  • 主类
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);
    }

}

启动测试

  • 访问接口

  • 控制台打印

拦截器的基本使用说完了。但它在实际的场景应用作用十分强大,慢慢在实践中探索吧

代码已经推送至github:https://github.com/NiuXiangQian/springboot-interceptor

正文到此结束
评论插件初始化中...
Loading...