配置登录拦截器
package com.lfsun.springbootsession.interceptor;
import com.lfsun.springbootsession.constants.Consts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* <p>
* 校验Session的拦截器
* </p>
*/
@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute(Consts.SESSION_KEY) != null) {
return true;
}
// 跳转到登录页
String url = "/page/login?redirect=true";
response.sendRedirect(request.getContextPath() + url);
return false;
}
}
mvc 配置类
package com.lfsun.springbootsession.config;
import com.lfsun.springbootsession.interceptor.SessionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* <p>
* WebMvc 配置类
* </p>
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private SessionInterceptor sessionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration sessionInterceptorRegistry = registry.addInterceptor(sessionInterceptor);
// 排除不需要拦截的路径
sessionInterceptorRegistry.excludePathPatterns("/page/login");
sessionInterceptorRegistry.excludePathPatterns("/page/doLogin");
sessionInterceptorRegistry.excludePathPatterns("/error");
// 需要拦截的路径
sessionInterceptorRegistry.addPathPatterns("/**");
}
}
完整代码案例地址
Spring Boot 集成 session