和springmvc大致相同,也是拦截器类实现interector接口,就是用一个类来代替springmvc.xml,该类要实现WebMvcConfigurer接口,作为springmvc的配置类。
拦截除了 / 和 /index的所有请求
package com.example.springbootdemo3.config;
import com.example.springbootdemo3.testfilter.firstInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
//代替原来的springmvc.xml文件,实现springmvc的自动化配置
//可以配置 视图解析器 拦截器 文件上传解析器 注解驱动 异常处理 组件扫描范围
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
// registry是整个拦截器的注册中心
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new firstInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/index");
}
}
package com.example.springbootdemo3.testfilter;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//1.设置拦截器实现handlerinterceptor接口,写拦截方法
//2.在spring定制化管理类的doInterceptors方法中添加该控制器
public class firstInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了");
HttpSession session= request.getSession();
if(session.getAttribute("user")==null)
{ System.out.println("拦截器跳转了");
response.sendRedirect("index");
}
return true;
}
}



