在 HttpServletRequest 中设置 Cookie

Akh*_*esh 1 java cookies servlets

有没有办法将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 );
Run Code Online (Sandbox Code Playgroud)

Yan*_*ski 7

我发送了 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.
}
Run Code Online (Sandbox Code Playgroud)

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