gpt4 book ai didi

java - httpservletrequest getCookies() 或 getHeader()

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:55:02 24 4
gpt4 key购买 nike

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

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?

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

最佳答案

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

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

关于java - httpservletrequest getCookies() 或 getHeader(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com