1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cookieの取得・設定・削除

Last updated at Posted at 2022-09-26

前提

name=test というCookieを操作する

Java

Cookieの取得

public Response get(@CookieValue(value="test", required=false) String cookieValue){
    String value = cookieValue; //SpringBootならこれでOK。簡単。
}

Cookieの設定

public void set(HttpServletRequest request, HttpServletResponse response){
    Cookie cookie = new Cookie("test", "value");
    cookie.setSecure(true);
    cookie.setHttpOnly(true);
    cookie.setPath("/cookie");
    response.addCookie(cookie); //生成したCookieをレスポンスに追加する。
}

Cookieの削除

public void delete(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if ("test".equals(cookie.getName())) {
            cookie.setMaxAge(0); //Cookieの最大有効期間を0秒に設定する。(=無効にする)
            response.addCookie(cookie);
        }
    }
}

JavaScript

Cookieの取得

var value = "";
for(var cookie of document.cookie.split(';')){
    if( cookie.split('=')[0] == 'test'){
        value = cookie.split('=')[1];
        break;
    }
}

Cookieの設定

document.cookie = 'test=value; path=/cookie;

Cookieの削除

document.cookie = "test=; max-age=0";

おまけ

Session idの取得方法

public SessionResponse getSession(HttpServletRequest request){
    HttpSession session = request.getSession();
    String sessionId = session.getId();
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?