1、首选创建一个继承HandlerInterceptor的拦截器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/*** 拦截器*/
public class MyInterceptor implements HandlerInterceptor{//在请求处理之前进行调用(Controller方法调用之前@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {HttpSession session = httpServletRequest.getSession();String user = (String) session.getAttribute("user"); //获取登录的session信息if(user!=null){return true;}else{
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index"); //未登录自动跳转界面return false;}}//请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandle被调用\n");}//在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion被调用\n");}
}
2、继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册自定义的拦截器:
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 WebMvcConfig implements WebMvcConfigurer {/*** 注册拦截器*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {//addPathPattern后跟拦截地址,excludePathPatterns后跟排除拦截地址registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/index").excludePathPatterns("/login/login"); }
}
这样我们就可以在用户请求到达controller层实现登录拦截了,所有用户请求都会被拦截,在prehandle方法进行登录判断,返回true则验证通过,否则失败