LoginSignup
8
7

More than 3 years have passed since last update.

Spring-Boot で Cookie の付与・取得・削除

Posted at

表題の通りです。

Cookie の付与

レスポンスボディにCookieを付与すればよい。

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

public String cookieTest(HttpServletResponse response) throws Exception {
    Cookie cookie = new Cookie("id", "this_is_the_testmessage"); // Cookieの作成
    cookie.setMaxAge(265 * 24 * 60 * 60); // Cookieの残存期間(秒数)
    cookie.setPath("/"); // Cookieの適用対象となるサーバ上のパス
    response.addCookie(cookie);
    return "content";
}

Cookie の取得

Cookieの取得は、Spring-bootでは@CookieValueアノテーションにて行う。

import org.springframework.web.bind.annotation.CookieValue;

public ModelAndView readCookie(@CookieValue(value="id", required=false) String sid, ModelAndView mav) {
  ...
}

Cookie の削除

Cookieの削除は、削除したいCookieの値をnullにし、残存期間を0秒に設定することで行う。したがって、以下のような手順となる。

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

public String deleteCookie(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if ("id".equals(cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
    return "content";
}
8
7
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
8
7