如何在出错时从后端删除 cookie
How to delete a cookie from backend upon an error
目前正在通过如下配置在 Spring 引导项目中设置仅 http cookie。
当我调用以下端点时,此 cookie 设置正确。
@Bean
public CookieSerializer defaultCookieSerializer() {
DefaultCookieSerializer cookie = new DefaultCookieSerializer();
cookie.setDomainNamePattern(".*");
cookie.setCookieName("my_cookie");
cookie.setUseSecureCookie(true);
cookie.setUseHttpOnlyCookie(true);
cookie.setCookieMaxAge(1200);
return cookie;
}
如您所见,名为 my_cookie
的 cookie 被设置为 2 分钟。
在同一项目的我的控制器中,我有以下控制器方法。
如果我进入错误块,我希望删除名为 my_cookie
的 cookie。我该怎么做?
这是我为此找到的最接近的问题,但考虑到我是通过配置设置的,这不是同一个问题。
@PostMapping(value = "/endpoint")
public List CustomResponse(
@RequestBody Request request,
) throws Exception {
CustomResponse response = null;
if (otherCookie != null) {
CustomResponse response = // perform some other rest request and get value from there
}
if (response == null) {
// I want to delete the cookie named `my_cookie` at this stage.
throw new CustomException('name');
}
return response;
}
要删除 cookie,请将 Max-Age 指令设置为 0 并取消设置它的值。您还必须传递用于设置它的相同的其他 cookie 属性。不要将 Max-Age 指令值设置为 -1。否则,它将被浏览器视为会话 cookie。
// create a cookie
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/");
//add cookie to response
response.addCookie(cookie);
更多请参考Dzone的post:
https://dzone.com/articles/how-to-use-cookies-in-spring-boot
目前正在通过如下配置在 Spring 引导项目中设置仅 http cookie。
当我调用以下端点时,此 cookie 设置正确。
@Bean
public CookieSerializer defaultCookieSerializer() {
DefaultCookieSerializer cookie = new DefaultCookieSerializer();
cookie.setDomainNamePattern(".*");
cookie.setCookieName("my_cookie");
cookie.setUseSecureCookie(true);
cookie.setUseHttpOnlyCookie(true);
cookie.setCookieMaxAge(1200);
return cookie;
}
如您所见,名为 my_cookie
的 cookie 被设置为 2 分钟。
在同一项目的我的控制器中,我有以下控制器方法。
如果我进入错误块,我希望删除名为 my_cookie
的 cookie。我该怎么做?
这是我为此找到的最接近的问题,但考虑到我是通过配置设置的,这不是同一个问题。
@PostMapping(value = "/endpoint")
public List CustomResponse(
@RequestBody Request request,
) throws Exception {
CustomResponse response = null;
if (otherCookie != null) {
CustomResponse response = // perform some other rest request and get value from there
}
if (response == null) {
// I want to delete the cookie named `my_cookie` at this stage.
throw new CustomException('name');
}
return response;
}
要删除 cookie,请将 Max-Age 指令设置为 0 并取消设置它的值。您还必须传递用于设置它的相同的其他 cookie 属性。不要将 Max-Age 指令值设置为 -1。否则,它将被浏览器视为会话 cookie。
// create a cookie
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/");
//add cookie to response
response.addCookie(cookie);
更多请参考Dzone的post: https://dzone.com/articles/how-to-use-cookies-in-spring-boot