1、创建拦截器
package com.example.demo.interceptor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 〈一句话功能简述〉 * 〈拦截器〉 * * @author 丶Zh1Guo * @create 2018/11/22 * @since 1.0.0 */public class LoginInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); // 在请求处理之前,只有返回true才会执行请求 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("[拦截器]启动登录状态拦截"); // 得到session HttpSession session = request.getSession(); logger.info("[拦截器]sessionID:" + session.getId()); // 得到用户信息 Object userInfo = session.getAttribute("userInfo"); //判断用户是否登录 if (userInfo != null) { logger.info("[拦截器]用户已经登录,用户名,密码:" + session.getAttribute("userInfo")); return true; } else { //不存在跳转至登录页 response.sendRedirect(request.getContextPath() + "/"); // 跳转到首页登录 logger.info("[拦截器]用户没有登录,已跳转到:" + request.getContextPath() + "/"); return false; } } // 视图渲染后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } // 请求处理后,视图渲染前 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}
2、.继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册自定义的拦截器
@Configuration 注解一定要有
package com.example.demo.interceptor;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * 〈一句话功能简述〉 * 〈自定义配置类〉 * * @author 丶Zh1Guo * @create 2018/11/22 * @since 1.0.0 */@Configurationpublic class LoginConfig implements WebMvcConfigurer { /** * 该方法用于注册拦截器 * 可注册多个拦截器,多个拦截器组成一个拦截器链 */ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 添加路径 // excludePathPatterns 排除路径 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/sys/*"); // 拦截sys路径下的url// .excludePathPatterns(""); }}
3、LoginController
/** * Copyright (C), 2017-2018, XXX有限公司 * FileName: LoginController * Author: 丶Zh1Guo * Date: 2018/11/22 11:10 * Description: 登录 * History: *
4、未登录会自动跳转到登录页面