package com.aaa.zxf.interceptor; import org.springframework.boot.autoconfigure.SpringBootApplication; 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; /** * 一、 springmvc 配置拦截器 * 1.1 创建在 web层下,新建一个interceptor 包。 * 1.2 新建一个类,继承WebMvcConfigurerAdapter * 1.3 重写addInterceptors 这个方法 * 在方法中,放入私有的方法, 设置需要拦截的路径。 * * 1.4 定义一个私有的方法 实现 HandlerInterceptor 中的方法。 * 返回一个HandlerInterceptor * * 二、 添加 @SpringBootApplication * */ @SpringBootApplication public class LoginInterceptor extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { // 拦截的路径 registry.addInterceptor(loginIntercepor()).addPathPatterns("/**"); } /** * 返回一个 HandlerInterceptor 类型 * @return */ private HandlerInterceptor loginIntercepor(){ HandlerInterceptor handlerInterceptor=new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("拦截器,被访问了!"); httpServletRequest.getSession(false); 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; } }