简体   繁体   English

httpservletrequest getCookies()或getHeader()

[英]httpservletrequest getCookies() or getHeader()

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? 当我读到如何在HTTP协议中传递cookie?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client). Cookie在请求(客户端 - >服务器)和响应(服务器 - >客户端)中作为HTTP标头传递。

getCookies , frees you from parsing the Cookie header string, and creating a java object out of it. getCookies ,使您免于解析Cookie头字符串,并从中创建一个Java对象。 Otherwise you will have to do something like: 否则你将不得不做以下事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM