登录拦截,请求的session里面有username者判断为登录状态
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
@Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
}
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
addInterceptor.excludePathPatterns("/error");
addInterceptor.excludePathPatterns("/plan/login**");
addInterceptor.addPathPatterns("/web/**");
}
private class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null)
return true;
String url = "/plan/logins";
response.sendRedirect(url);
return false;
}
}
}
使用redis 进行增强。
获取的session 去判断在redis里面是否存在,存在可登录成功
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
@Autowired
private RedisTemplate redisTemplate;
private RedisTemplate userredis(RedisTemplate redisTemplate) {
redisTemplate = RedisDbInit.initRedis(RedisConfig.userreidport, redisTemplate);
return redisTemplate;
}
@Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
}
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
addInterceptor.excludePathPatterns("/error");
addInterceptor.excludePathPatterns("/plan/login**");
addInterceptor.addPathPatterns("/web/**");
}
private class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String url = "/plan/logins";
HttpSession session = request.getSession();
if (session.getAttribute("username") != null){
String name= (String) userredis(redisTemplate).opsForValue().get(session.getAttribute("username"));
if (name==null){
response.sendRedirect(url);
return false;
}else {
return true;
}
}
response.sendRedirect(url);
return false;
}
}
}