springboot2 拦截器无效

在网上找了好多,基本上都一个样,按照一步一步来,都是无效,下面是我的配置:

Config:

import com.example.demo.interceptor.OneInterceptor;
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 InterceptorConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new OneInterceptor()).addPathPatterns("/**");
}

}

OneInterceptor:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 OneInterceptor implements HandlerInterceptor {

private Logger logger = LoggerFactory.getLogger(OneInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
    logger.debug("拦截。。。");
    return false;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    System.err.println("post");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    System.err.println("after");
}

}

无论访问什么路径都不会走拦截器,
不知道哪里配置错了,求大神解答!

阅读 8.5k
2 个回答

不知道访问路径的时候会不会打印“拦截。。。”?

上面的OneInterceptor的preHandle方法要返回true才会执行下去,加了@Component就不用new了

@Component
public class OneInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        System.out.println("pre");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.err.println("post");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.err.println("after");
    }
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    private final OneInterceptor oneInterceptor;

    @Autowired
    public InterceptorConfig(OneInterceptor oneInterceptor) {
        this.oneInterceptor = oneInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(oneInterceptor).addPathPatterns("/**");
    }
}

你这配置没问题的,你看看日志有没有logger.debug("拦截。。。");
另外,声明OneInterceptor为组件之后,不需要new,使用的时候注入就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏