Java-Servlet操作Cookie

本文介绍如何操作Servlet中的Cookie。

获取Request中的Cookie

1
2
3
4
5
6
7
8
9
10
11
public static String getCookie(final HttpServletRequest request, final String name){
final Cookie[] cookies = request.getCookies();
if (cookies != null){
for (final Cookie cookie : cookies){
final String sName = cookie.getName();
if (sName.equals(name))
return cookie.getValue();
}
}
return null;
}

往Response中写入Cookie

1
2
3
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.addCookie(new Cookie("id", "xiaoming"));
}

转换httpClient中的Cookie

httpClient中的Cookie操作,参考利用httpClient进行https访问,httpClient中的Cookie和servlet中的Cookie类型不同,需要进行转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private static Cookie servletCookieFromApacheCookie(org.apache.http.cookie.Cookie apacheCookie) {
if(apacheCookie == null)
return null;

String name = apacheCookie.getName();
String value = apacheCookie.getValue();
Cookie cookie = new Cookie(name, value);

value = apacheCookie.getDomain();
if(value != null)
cookie.setDomain(value);

value = apacheCookie.getPath();
if(value != null)
cookie.setPath(value);

value = apacheCookie.getComment();
if(value != null)
cookie.setComment(value);

cookie.setVersion(apacheCookie.getVersion());
Date expiryDate = apacheCookie.getExpiryDate();
if(expiryDate != null) {
long maxAge = (expiryDate.getTime() - System.currentTimeMillis()) / 1000;
cookie.setMaxAge((int) maxAge);
}

return cookie;
}