java 在 HttpServletRequest 中设置 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33121630/
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-11-02 21:13:30  来源:igfitidea点击:

Set Cookie in HttpServletRequest

javaservletscookies

提问by Akhilesh

is there any way to add cookie to HttpServletRequest

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

Please help me..

请帮我..

i have tried this. but its not working

我试过这个。但它不工作

   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 );

回答by Yan Khonski

I sent cookies in response. This is how I did it:

我发送了 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.
}

If you want to redirect or forward your request to the next jsp, servlet, etc, add request attribute see Difference between getAttribute() and getParameter()

如果要将请求重定向或转发到下一个 jsp、servlet 等,请添加请求属性,请参阅getAttribute() 和 getParameter() 之间的区别