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。

  • 相关阅读:
    request和request.form和request.querystring的区别
    PL/SQL Developer连接64位Oracle
    C# Winform控件对透明图片重叠时导致图片不透明的解决方法
    C++11多线程编程-两个进程轮流打印1~100
    使用 C++11 并发编程入门
    STL vector动态扩容
    GDB入门教程
    统计整数中1的个数
    gulp的使用
    nvm安装教程
  • 原文地址:https://www.cnblogs.com/wulisz/p/14836933.html
Copyright © 2011-2022 走看看