如何存储和读取cookis
我想做的和CSND登陆一样,能记住的,用户名和密码的,不用每次都登陆的,
------解决方案--------------------实现和csdn登陆一样的功能,不仅仅把用户的信息写到cookie里那么简单啊。
用户的登陆信息要写到后台的数据库中的。而且定时还要把用户的信息删掉。
我想csdn后台的数据库表里最少应该存放用户登录名,ip,登陆时间这些信息吧。具体的慢慢想吧,这样才能有所提高阿。
写cookie很简单的javascript代码里有cookie对象。在jsp里也有cookie对象的。
------解决方案--------------------public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie cookies[] = request.getCookies();
if (cookies == null || name == null || name.length() == 0)
return null;
Cookie cookie = null;
for (int i = 0; i < cookies.length; i++) {
if (!cookies[i].getName().equals(name))
continue;
cookie = cookies[i];
if (request.getServerName().equals(cookie.getDomain()))
break;
}
return cookie;
}
public static void deleteCookie(HttpServletRequest request,
HttpServletResponse response, Cookie cookie) {
if (cookie != null) {
String path = request.getContextPath() != null ? request.getContextPath()
: "/ ";
if ( " ".equals(path))
path = "/ ";
cookie.setPath(path);
cookie.setValue( " ");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
public static void setCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value) {
setCookie(request, response, name, value, 0x278d00);
}
public static void setCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value, int maxAge) {
if (value == null)
value = " ";
String path = request.getContextPath() != null ? request.getContextPath()
: "/ ";
if ( " ".equals(path))
path = "/ ";
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
cookie.setPath(path);
response.addCookie(cookie);
}