Cookie does not work in Internet Explorer

I am adding a cookie value with

Cookie testcookie = new Cookie ("test",test);
testcookie .setMaxAge(5*60);
response.addCookie(testcookie) ;

But I do not get cookie value in Internet Explorer. cookie retrieval code

Cookie cookies [] = getRequest().getCookies ();
    Cookie myCookie = null;
    if (cookies != null)
    {

        for (int i = 0; i < cookies.length; i++) 
        {
            if (cookies [i].getName().equals ("test"))
            {
                myCookie = cookies[i];
                String testval=myCookie.getValue();
            }
        }
    }

But the same thing works in firefox, cooies are included in IE. How to solve this?

+3
source share
2 answers

These days I ran into the same problem and I found a solution. Try manually javax.servlet.http.Cookiesetting the cookie, as it doesn’t allow you to set the attribute Expires:

StringBuilder cookie = new StringBuilder("test=" + test + "; ");

DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5*60);
cookie.append("Expires=" + df.format(cal.getTime()) + "; ");
cookie.append("Max-Age=" + (5*60));
response.setHeader("Set-Cookie", cookie.toString());

Hope this helps

+1
source

SimpleDateFormat , , cookie , . , , GMT. GMT String.format, .

// Your values here
String name = "test";
String value = "test";
String path = "/";
int maxAge = 60;


StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append("=");
sb.append(value);

sb.append("; path=");
sb.append(path);

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.add(Calendar.SECOND, maxAge);
sb.append("; Expires=");
sb.append(String.format(Locale.US, "%1$ta, %1$td-%1$tb-%1$tY %1$tH:%1$tM:%1$tS GMT", cal));
sb.append("; Max-Age=");
sb.append(maxAge);

response.setHeader("Set-Cookie", sb.toString());
0

Source: https://habr.com/ru/post/1728582/


All Articles