Cookie Value not preserved in a flow containing 3 pages for first 2 Pages involving Form Submit on Post Request and setting cookies via Servlet

I have a Form containing some information to be preserved in cookies on Submitting of Form via POST action .

After redirection to Next Page and having same Form i want my cookie to be updated with more information from this Page and on Submit button Form will be Posted via Form Action .

Then on coming to plain next page , i want my cookie information to be displayed on this page containing information from 2 Forms on 2 Different Pages .

But i see what is happening is cookie containing information only about 1st form in browser console on 3rd Page, but not of 2nd Form , but also printing correct value of cookie i.e both 1st and 2nd page in servlet logs .

The Approach i followed is :

I have a Form in first Page having a particular action . Then on Submit of Form i call Post method of servlet at same action .

   doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    Cookie cookie = request.getCookie('formInfo')

    if (!cookie) {
                cookie = new Cookie('formInfo', Information)
                cookie.path = '/'
                cookie.maxAge = 60 * 60 * 24 
            } else { //if formInfo is not empty, adding the data to the cookie
                cookie.setValue(Information)
            }
              response.addCookie(cookie)

            //a redirect to the location of the next question
             response.setStatus(302) 
             response.addHeader('Location', Next Page)
}

Then it Goes to 2nd Page having Form with same action as First , then on Submitting have the same servlet call on Post method and then redirects to third page which is on which i have to show cookie value from 2 pages .

But i see what is happening is cookie containing information only about 1st form in browser console on 3rd Page, but not of 2nd Form , but also printing correct value of cookie i.e both 1st and 2nd page in servlet logs .

It is configured on my end that after 1st Form submit , should go to which page and after 2nd Form Submit Should go to which page .

I earlier thought request is lost for 2nd Page , so tried with Request Dispatcher but it redirects to form action and not on next Page.

So , need inputs on how to solve issue listed in Bold .


Source: forms

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.