springboot 拦截器,源码demo

2022-07-10 10:18:58

拦截器继承org.springframework.web.servlet.HandlerInterceptor接口
自定义拦截器继承 HandlerInterceptor,根据需要重写 preHandle , postHandle ,afterCompletion这3个方法。
这3个拦截器执行过程参考下图

过滤器、拦截器 流程图
在这里插入图片描述

流程图来自 https://www.cnblogs.com/jeffwongishandsome/p/spring-boot-use-filter-and-interceptor-to-implement-an-easy-auth-system.html

由上面拦截器在一个web请求过程中处理流程可知,要想在一个请求controller之前处理关心的拦截信息,需要在preHandle方法中处理.

测试源码

下面 demo,通过 自定义拦截器中 拒绝 用户名为 ‘zhangsan’ 的请求

springboot 项目interceptor_demo 的目录结构如下:
在这里插入图片描述
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 http://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.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>interceptor_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>interceptor_demo</name>
    <description>Demo project for Spring Boot</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</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>

配置文件application.properties,只配置web server 端口

server.port=8089

自定义拦截器 TestInterceptor

package com.example.interceptor_demo.interceptor;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.PrintWriter;@ComponentpublicclassTestInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        String name= request.getParameter("name");if("zhangsan".equals(name)){//拒绝zhangsan的请求
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(403);
            PrintWriter writer= response.getWriter();
            writer.write("静止访问");//false 表示这个处理不再往下执行,不会进入controllerreturnfalse;}//true 继续往下执行 进入controllerreturntrue;}}

注册拦截器 WebConfigurer

package com.example.interceptor_demo.interceptor;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassWebConfigurerimplementsWebMvcConfigurer{@Autowiredprivate TestInterceptor loginInterceptor;/**
     * 这个方法是用来配置静态资源的,比如html,js,css,等等
     */@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistry registry){}/**
     * 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
     * @param registry
     */@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){// addPathPatterns("/**") 表示拦截所有的请求,// addPathPatterns("/test/**") 表示拦截/test/ 下的所有路径请求,// addPathPatterns("/test/*") 表示拦截/test/abc,拦截/test/aaa , 不拦截 /test/abc/def// addPathPatterns("/test/**").excludePathPatterns("/test/login", "/test/register") 表示拦截/test/ 下的所有路径请求,但不拦截 /test/login 和 /test/register
        registry.addInterceptor(loginInterceptor).addPathPatterns("/test");}}

测试类 TestController

package com.example.interceptor_demo.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublicclassTestController{@RequestMapping("/test")public Stringtest(){return"access success";}}

启动类 InterceptorDemoApplication

package com.example.interceptor_demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Configuration;@SpringBootApplicationpublicclassInterceptorDemoApplication{publicstaticvoidmain(String[] args){
        SpringApplication.run(InterceptorDemoApplication.class, args);}}

测试

启动后,浏览器输入 127.0.0.1:8089/test?name=zhangsan
在这里插入图片描述

浏览器输入 127.0.0.1:8089/test?name=lisi

在这里插入图片描述

源码

链接:https://pan.baidu.com/s/183h87UI4S3OpRjWBNdBJPA
提取码:20o1

下一章介绍 解决拦截器读取post请求body内容后controller中 @RequestBody 参数无法读取body 内容问题

  • 作者:无、涯
  • 原文链接:https://blog.csdn.net/a704397849/article/details/97260663
    更新时间:2022-07-10 10:18:58