gpt4 book ai didi

java - 在 HttpServletRequest 中设置 Cookie

转载 作者:行者123 更新时间:2023-12-01 18:10:50 25 4
gpt4 key购买 nike

有什么办法可以将cookie添加到HttpServletRequest

请帮助我..

我已经尝试过这个。但它不起作用

   HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String cookie = request.getHeader(HttpHeader.AUTHORIZATION.asString());
HttpRequest httpRequest = new HttpRequest().setRequest(request);
String authCookie = String.format("%s=%s", session_id, cookie );
ServletRequest clientRequest = httpRequest.getRequest();
httpRequest.setCookies(authCookie );

最佳答案

我发送了 cookie 作为响应。我就是这样做的:

String contextPath = request.getContextPath();//We need this path to set cookie's path.
Cookie [] cookies = request.getCookies();
Cookie cookieToProcess = null;
for (Cookie cookie : cookies) {
//Search cookie you need.
if ("you-cookie-name".equals(cookie.getName()) && "your-coocie-path".equals(cookie.getPath())) {
cookieToProcess = cookie;
break;
}
}
if (cookieToProcess == null) {
//No such cookie.
//Possibly user enters your site for the first time or they disabled cookies.
//In this case we create a new cookie.
String cookieName = "your-cookie-name";
String cookieValue = "your-cookie-value";
Cookie newCookie = new Cookie(cookieName, cookieValue);
newCookie.setPath(contextPath);
response.addCookie(newCookie);
} else {
String cookieValue = cookieToProcess.getValue();//Retrieve value from the cookie.
}

如果你想将你的请求重定向或转发到下一个jsp、servlet等,请添加request属性请参阅Difference between getAttribute() and getParameter()

关于java - 在 HttpServletRequest 中设置 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121630/

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