zoukankan      html  css  js  c++  java
  • Spring Boot 拦截器

    首先,需要一个自定义拦截器,这个拦截器需要实现HandlerInterceptor接口

    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    @Component
    public class MyInterceptor implements HandlerInterceptor {
        // false 拦截    true 通行
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            return false;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            
        }
    }

    然后在三个Handle里面完成自己的逻辑

    填写完成之后,需要将这个类注册为拦截器

    另建一个拦截器配置类,添加@Configuration注解

    package cnki.tpi.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.WebMvcConfigurer;
    
    @Configuration
    public class myInterceptorConfig implements WebMvcConfigurer {
    
        @Autowired
        private MyInterceptor myInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor)
              .addPathPatterns(
    "/**") .excludePathPatterns("/aaa/**"); } }

    此时需要注意的是,拦截器一定是通过@Autowired注入的,而不是在registry.addInterceptor(new MyInterceptor())是通过new出来的,不然会造成在MyInterceptor类的方法中,所有通过@Autowird注入进来的类都为null。

  • 相关阅读:
    Docker 安装ELK之 zz
    Linux使用Aria2命令下载BT种子/磁力/直链文件 转载
    新路由3newifi3路由器刷机newifi3breed解锁小白刷机教程路由器刷breed老毛子Padavan固件
    从ServerSwitch到SONiC Chassis:数据中心交换机技术的十年探索历程
    SONiC项目的发展及其相关介绍(转载)
    linux后台运行和关闭、查看后台任务
    tsar安装和使用
    浅谈CLOSE_WAIT
    贾扬清牛人(zz)
    Linux Soft-RoCE implementation (zz)
  • 原文地址:https://www.cnblogs.com/wulisz/p/14836933.html
Copyright © 2011-2022 走看看