您的位置:首页 > 其它

关闭浏览器后session不失效 in servlet.

2012-07-23 16:05 218 查看
重新学习session,为了使一个session在浏览器关闭仍能使用,看了看response的set-cookie格式。写了servlet测试如下:

/**
* @author Zhou Hao, Fri, 20 Jul 2012 20:11:14 EST
*
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// This method is used to test the functionality through which session information
// can be retrieved even if a browser has been closed.
// This is achieved by setting related HTTP response header, that it, "Set-Cookie".
// The implementation of getSession() will not specify the age of the cookie (named as JSESSIONID),
// which means that a programmer has to reset the expiration information manually.

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(false);
if(session !=null){
// if session has been set, just show it.
out.print(session.getId());
}else{
out.print("no session<br/>");
HttpSession session2 = request.getSession();
Collection<String> names = response.getHeaderNames();
for (String name : names) {
if("Set-Cookie".equals(name)){
// Get GMT timezone
TimeZone zone = TimeZone.getTimeZone("GMT");
// For testing purpose, I just set the expiration time as 2 minute after from now on.
Date d = new Date(System.currentTimeMillis()+60*1000);
// Set the date format in Set-Cookie header in accordance with HTTP specification.
// Example: "Set-Cookie ...;Expires=Wed, 09 Jun 2021 10:18:14 GMT".
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
// Set timezone as GMT.
//The SimpleDateFormat will convert the default timezone (in this machine is EST)
// to GMT timezone.
sdf.setTimeZone(zone);
// Format the date.
String date = sdf.format(d);
// Append the expiration information to response header Set-Cookie
response.setHeader(name, response.getHeader(name)+"; Expires="+date);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息