springboot配置mvc拦截器

Posted M87星云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot配置mvc拦截器相关的知识,希望对你有一定的参考价值。

1、导入依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/>
    </parent>
    
    <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>

2、配置controller

@Controller
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/show")
    @ResponseBody
    public String show(){
        return "hello world!";
    }

}

3、创建Interceptor拦截器

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器执行中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器执行后");
    }
}

4、配置拦截器

@Configuration
public class MyWebConfiguration implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         *  addPathPatterns 拦截的资源,/** 表示拦截所有多级资源
         *  excludePathPatterns 不拦截的资源 aa.js
         */
        registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/aa.js");
    }
}

5、springboot目录结构

 

 6、测试拦截器

访问 http://localhost:8080/hello/show,提示如图信息表示拦截器配置成功

 

以上是关于springboot配置mvc拦截器的主要内容,如果未能解决你的问题,请参考以下文章

springboot登陆拦截器

SpringBoot支持interceptor(拦截器)

SpringBoot中静态资源访问方案

Springboot中如何访问静态资源?

spring拦截器HandlerInterceptorAdapter,能不能控制范围?

Java 微服务 day02 源代码 SpringBoot 实战开发 SpringMVC高级配置:拦截器:HandlerExecutionChain