Jayz
Jayz

Reputation: 1174

Cookie lost on multiple requests (spring mvc + jsp)

I set my cookie in my controller, return a new modelandview, the cookie gets set. However, on any other request, the cookie is lost.

Also, when I reset the cookie to some other value, the value doesn't change when the page is loaded. It does change after page refresh and it again gets lost on any other request.

During all these multiple requests, JSESSIONID remains the same.

In controller:

Cookie locationCookie = new Cookie("locCookie", loc);
locationCookie.setMaxAge(60*60*24*365); //one year
response.addCookie(locationCookie);

return FWD_HOME;

In JSP (FWD_HOME):

<jsp:include page="/WEB-INF/jsp/fragments/header.jsp"></jsp:include>
<jsp:forward page="/HOME"></jsp:forward>

In JSP (header):

        <%
           Cookie cookie = null;
           Cookie[] cookies = null;
           cookies = request.getCookies();
           String locValue = null;
           if( cookies != null ){
              for (int i = 0; i < cookies.length; i++){
                 cookie = cookies[i];
                 out.print(cookie.getName()+"=");
                 out.print(cookie.getValue()+";");
                 if("locCookie".equals(cookie.getName())){
                     locValue = cookie.getValue();
                 }
              }
          }
           out.print(locValue);
        %>

What am I doing wrong here?

Upvotes: 0

Views: 3147

Answers (1)

Jayz
Jayz

Reputation: 1174

I got the solution. along with Cookies on localhost with explicit domain, setting the path to "/" made it work.

Upvotes: 3

Related Questions