使用JDK自带缓存(Cache)实现Cookie自动登陆

自定义一个缓存类AdminCache

package jw.admin.common;

import jw.base.entity.Admin;
import sun.security.util.Cache; public class AdminCache { //第一个参数表示cache对象中允许添加的键值对数量,第二个参数表示缓存的时间,单位是秒
private static Cache cache = Cache.newHardMemoryCache(0,3600 * 24 * 7); public static Admin get(String key){
return (Admin)cache.get(key);
}
public static void set(String key,Admin admin){
AdminCache.cache.put(key,admin);
} }

登陆成功发送Cookie到客户端并保存到缓存中

//如果选择记住登录状态,把用户签名保存到cookie中,把签名和签名的对象保存到缓存中
if (remember == true){
Cookie cookie = new Cookie("adminSign",admin.sign());
cookie.setMaxAge(60 * 60 * 24 * 7);
cookie.setPath("/");
response.addCookie(cookie);
AdminCache.set(admin.sign(),admin);
}

在spring-servlet中配置拦截器路径

<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<bean class="jw.admin.interceptor.AuthInterceptor"/>
<bean class="jw.admin.interceptor.AuthCookieInterceptor"/>
</mvc:interceptors>

拦截器内容

package jw.admin.interceptor;

import jw.admin.common.AdminCache;
import jw.base.entity.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class AuthCookieInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(); //判断session中的用户信息是否存在,不存在从cookie中获取然后装如session
if(session.getAttribute("admin") == null){
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(int i = 0; i < cookies.length; i++){
if(cookies[i].getName().equals("adminSign")){
String sign = cookies[i].getValue();
Admin admin = AdminCache.get(sign); //根据签名获取用户的完整信息装如session
session.setAttribute("admin",admin);
break;
}
}
}
}
return true;
} @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 { }
}
上一篇:Windows PHone 8 获取硬件信息


下一篇:UVa 10305 - Ordering Tasks (拓扑排序裸题)