package com.zs.springboot.interceptor; import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 创建一个拦截器,在ssm框架中,创建拦截器时需要在xml做如下配置 * <mvc:interceptors> * <mvc:interceptor> * <mvc:mapping path="/**"/> * <mvc:exclude-mapping path="/login"/> * <bean class=""/> * </mvc:interceptor> * </mvc:interceptors> * 上面的配置如果使用springboot该如何使用java类配置? * 1.创建一个配置类,继承mvc配置适配器,表示这是一个mvc配置文件 */ @SpringBootConfiguration public class MvcInterceptorConfig extends WebMvcConfigurerAdapter { /** * 实现添加拦截器的方法 * @param registry:拦截器注册器,相当于<mvc:interceptors>标签 */ @Override public void addInterceptors(InterceptorRegistry registry) { /** * 实现注册方法添加拦截器:相当于 * <mvc:interceptor> * <mvc:mapping path="/**"/> * <mvc:exclude-mapping path="/login"/> * <bean class=""/> * </mvc:interceptor> * */ registry.addInterceptor(loginIngerceptor()).addPathPatterns("/**").excludePathPatterns("/login"); } private HandlerInterceptor loginIngerceptor() { HandlerInterceptor handlerInterceptor = new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("我是拦截器,我被访问了"); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }; return handlerInterceptor; } }