Expires string in cookie header

前端 未结 4 1214
一整个雨季
一整个雨季 2021-02-13 11:59

Simple question I think, but I just can\'t seem to find an answer.

I am writing a cookie in a Java Servlet with the Cookie class which is sent to the browser in the resp

4条回答
  •  无人及你
    2021-02-13 12:33

    The first answer given by JasonStoltz is the correct one:

    1) Apache Commons HTTPClient project has a "DateUtil" class that I was hoping would work. http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/util/DateUtil.html. This provides convenience methods to format the date into a few standard formats to communicate dates in http headers... however, none of them seemed to match exactly what was being returned by the servlet container.

    Use a DateTime library to get a date object for one hour in the future (or whatever time), and then use the Apache DateUtil class. That class outputs according to the RFC, so you do not have to worry that it does not match what your servlet 'usually produces' - browsers will respect the RFC!

    Your code will look something like this:

    // for one hour later (should probably use date libraries in general, this is somewhat awkward)
    Date expiresDate = new Date(new Date().getTime() + 3600*1000); 
    response.setHeader("Set-Cookie", "Expires=" + DateUtil.formatDate(expiresDate) + ";");
    

提交回复
热议问题