zoukankan      html  css  js  c++  java
  • 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,提示如图信息表示拦截器配置成功

  • 相关阅读:
    MySQL数据库学习【第三篇】增删改查操作
    MySQL数据库学习【第二篇】基本操作和存储引擎
    MySQL数据库学习【第一篇】数据库安装
    python全栈开发基础【第二十七篇】IO模型
    python全栈开发基础【第二十六篇】(concurrent.futures模块、协程、Greenlet、Gevent)
    python基础之带参数装饰器和迭代器
    python基础之闭包函数与装饰器
    逻辑回归
    朴素贝叶斯
    决策树
  • 原文地址:https://www.cnblogs.com/M87-A/p/14905894.html
Copyright © 2011-2022 走看看