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。

  • 相关阅读:
    从大量的IP访问记录中找到访问次数最多的IP
    打赏功能的实现
    MFC通过ODBC连接Mysql程序
    VC++中使用MFC通过ADO连接数据库
    MySQL 5.1参考手册
    MFC ADO mysql 经验总结一
    VC连接MySQL
    VC连接MySQL
    MFC使用ADO对象开发数据库应用程序
    MFC中用Ado连接数据库
  • 原文地址:https://www.cnblogs.com/wulisz/p/14836933.html
Copyright © 2011-2022 走看看