Java httpservletrequest getCookies() 或 getHeader()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33690741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:54:44  来源:igfitidea点击:

httpservletrequest getCookies() or getHeader()

javaservlets

提问by Yan Khonski

I want to accept data from a client. What are the pros and cons of each approach?

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

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.
     }
}

or

或者

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

As I read How are cookies passed in the HTTP protocol?

正如我所读到的,cookie 是如何在 HTTP 协议中传递的?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

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

采纳答案by Optional

getCookies, frees you from parsing the Cookie header string, and creating a java object out of it. Otherwise you will have to do something like:

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.