springboot配置拦截器 - session过期跳至登录页

第一步: 创建拦截器

/**
 * 定义拦截器
 */
@Component
@Log4j
public class ConfigInterceptor implements HandlerInterceptor{

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
        // 从session中获取用户信息
        Personnel comUser = (Personnel) session.getAttribute("user");
        
        // session过期
        if(comUser == null){ 
        	log.info(">>>session过期, 跳至登录页");
            response.sendRedirect("/outToLogin"); // 通过接口跳转登录页面, 注:重定向后下边的代码还会执行 ; /outToLogin是跳至登录页的后台接口
            return false;
        }else{
        	return true;
        }
    }
}

第二步: 配置拦截器规则

@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter{
	
        /**
	 * 注入第一步定义好的拦截器
	 */
    @Autowired
    private ConfigInterceptor configInterceptor;

    /**
     * 定义拦截规则, 根据自己需要进行配置拦截和排除的接口
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(configInterceptor)
        // .addPathPatterns() 是配置需要拦截的路径 
        .addPathPatterns("/**")
        // .excludePathPatterns() 用于排除拦截
        .excludePathPatterns("/") // 排除127.0.0.1进入登录页
        .excludePathPatterns("/code") // 排除登录页获取验证码接口
        .excludePathPatterns("/loginVerify") // 排除验证账号密码接口
        .excludePathPatterns("/outToLogin")
        .excludePathPatterns("/lib/**") // 排除静态文件
        .excludePathPatterns("/js/**")
        .excludePathPatterns("/img/**")
        .excludePathPatterns("/css/**");
    }
}

第二步的配置拦截规则也可以这样定义

@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter{ 
     
       // 需要走拦截器的接口
	private static List list;
	
	static{
        // 通过静态代码块开启项目只执行一次,  
		list = new ArrayList();
		list.add("/professor/**"); // 需要拦截的接口
		list.add("/technology/**");
		list.add("/civilCompany/**");
		list.add("/admin/**");
	}
	
    public void addInterceptors(InterceptorRegistry registry) {
       // new ConfigInterceptor()是第一步定义的拦截器
        registry.addInterceptor(new ConfigInterceptor()).addPathPatterns(list);
    }

}

注: 如果接口类型不多的情况下推荐通过静态代码块方式进行实现, 这样更灵活;

你可能感兴趣的:(springboot)