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。

posted @ 2021-06-01 14:02  代码羡  阅读(120)  评论(0编辑  收藏  举报