在HttpServletRequest中设置Cookie

时间:2015-10-14 09:32:12

标签: java servlets cookies

有没有办法将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 );

2 个答案:

答案 0 :(得分:4)

我发送了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等,请添加请求属性 见Difference between getAttribute() and getParameter()

答案 1 :(得分:-1)

我发现的唯一方法是创建一个扩展 HttpServletRequestWrapper 的自定义请求包装器

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Arrays;
import java.util.List;

public class CustomRequestWrapper extends HttpServletRequestWrapper {

    private List<Cookie> cookies;

    public CustomRequestWrapper(HttpServletRequest request) {
        super(request);
        this.cookies = Arrays.asList(request.getCookies());
    }

    @Override
    public Cookie[] getCookies() {
        return this.cookies.toArray(new Cookie[0]);
    }

    public void addCookie(Cookie cookie) {
        this.cookies.add(cookie);
    }
}

通过这种方式,您可以轻松地在类中的 List 中删除或添加 cookie,并且 requests getCookies() 方法将返回您修改后的 cookie 列表。请注意,尽管 cookie 有一个单独的 getCookies() 方法,但它们最终只是 http 标头,因此 getHeaders() 方法不会返回您修改后的 cookie 列表在 Cookie 标头中。如果您希望 getHeaders() 工作,您还必须覆盖该方法。