httpservletrequest getCookies()或getHeader()

时间:2015-11-13 10:34:34

标签: java servlets

我想接受来自客户的数据。 每种方法的优缺点是什么?

HttpServletRequest request = retriveRequest();
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
     if ("my-cookie-name".equals(cookie.getName())) {
          String value = cookie.getValue();
         //do something with the cookie's value.
     }
}

String request.getHeader("header-name");

当我阅读How are cookies passed in the HTTP protocol?

  

Cookie在请求(客户端 - >服务器)和响应(服务器 - >客户端)中作为HTTP标头传递。

1 个答案:

答案 0 :(得分:10)

getCookies,使您免于解析Cookie标头字符串,并从中创建一个Java对象。否则你将不得不做类似的事情:

String rawCookie = request.getHeader("Cookie");
String[] rawCookieParams = rawCookie.split(";");
for(String rawCookieNameAndValue :rawCookieParams)
{
  String[] rawCookieNameAndValuePair = rawCookieNameAndValue.split("=");
}
// so on and so forth.