如何用 Spring 将 'Cookie' header 解析为 `javax.servlet.http.Cookie`?

How to parse the 'Cookie' header into `javax.servlet.http.Cookie` with Spring?

我想将来自 http 请求的 cookie header 的值解析为 javax.servlet.http.Cookie 实例。

例如,请求中的 Cookie

Cookie: HSID=AYQEVnDKrdst; Domain=.foo.com; Path=/aaa; HttpOnly

spring 是否提供任何实用程序来轻松解析它?我不想手动解析它或涉及其他一些库

WebUtils 提供了一个 getCookie 方法 - WebUtils.getCookie

Cookie cookieName=WebUtils.getCookie(request,this.COOKIE_NAME);
String cookieValue = cookieName.getValue();

您可以尝试在控制器方法中使用注释:

@CookieValue("Cookie") String cookie

然后使用Java内置解析方法:

String[] cookieValues = StringUtils.split(cookie, ";");

或使用扫描仪:

Scanner scan = new Scanner(cookie).useDelimiter(";");
while(scan.hasNext()){
...
}

Spring 提供 @CookieValue 作为处理程序方法参数的注释。它既支持 Cookie 作为参数类型,又支持 Stringint

Annotation which indicates that a method parameter should be bound to an HTTP cookie. Supported for annotated handler methods in Servlet and Portlet environments.

The method parameter may be declared as type javax.servlet.http.Cookie or as cookie value type (String, int, etc).

在幕后,它使用 WebUtils#getCookie 将值解析为 Cookie