Java 怎么将会话(Session)ID写入cookie

2019年8月15日22:59:15 评论 26

1.简介

Java 怎么将会话(Session)ID写入cookie?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class Main{
    private static final String DISTRIBUTED_SESSION_ID = "JSESSIONID";
    
    public static Cookie writeSessionIdToCookie(String id,
            HttpServletRequest request, HttpServletResponse response,
            int expiry) {
        Cookie cookie = findCookie(DISTRIBUTED_SESSION_ID, request);
        if (cookie == null) {
            return writeSessionIdToNewCookie(id, response, expiry);
        } else {
            cookie.setValue(id);
            cookie.setMaxAge(expiry);
            response.addCookie(cookie);
        }
        return cookie;
    }
    
    public static Cookie findCookie(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (int i = 0, n = cookies.length; i < n; i++) {
            if (cookies[i].getName().equalsIgnoreCase(name)) {
                return cookies[i];
            }
        }
        return null;
    }
    
    public static Cookie writeSessionIdToNewCookie(String id,
            HttpServletResponse response, int expiry) {
        Cookie cookie = new Cookie(DISTRIBUTED_SESSION_ID, id);
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
        return cookie;
    }
}

 

3.总结

示例代码演示了 Java 怎么将会话(Session)ID写入cookie,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: