response.addCookie() then RequestDispatcher forward but no cookie

I am having an issue with cookies here. In a webapp I use a jsp form to log a user in. The user clicks on submit and gets to LoginServlet. It’s doPost method, verifies username and password and if correct adds cookies. Then it Redirects to the HomeServlet. But when I check for cookies on the home servlet i get nothing except from the jsessionID. The code is :

Cookie userlastNameCookie = new Cookie("user_last_name", user.getLastName());
    userlastNameCookie.setDomain("127.0.0.1");
    userlastNameCookie.setPath("/App/");
    userlastNameCookie.setMaxAge(30*60);

    Cookie userEmailCookie = new Cookie("user_email", user.getEmail());
    userEmailCookie.setDomain("127.0.0.1");
    userEmailCookie.setPath("/App/");
    userEmailCookie.setMaxAge(30*60);

    String userUniqueIdString= Integer.toString(user.getUniqueId());
    Cookie userUniqueIdCookie = new Cookie("user_uuid",userUniqueIdString);
    userUniqueIdCookie.setDomain("127.0.0.1");
    userUniqueIdCookie.setPath("/App/");
    userUniqueIdCookie.setMaxAge(30*60);

    String userId = Integer.toString(user.getUserId());
    Cookie userIdCookie = new Cookie("user_id",userId);
    userIdCookie.setDomain("127.0.0.1");
    //userIdCookie.setPath("/App/");
    userIdCookie.setMaxAge(30*60);

    Cookie userHashCookie = new Cookie("hash", user.getHash());
    userHashCookie.setDomain("127.0.0.1");
    //userHashCookie.setPath("/App/");
    userHashCookie.setMaxAge(30*60);



    resp.addCookie(usernameCookie);
    resp.addCookie(userfirstnameCookie);
    resp.addCookie(userlastNameCookie);
    resp.addCookie(userEmailCookie);
    resp.addCookie(userUniqueIdCookie);
    resp.addCookie(userIdCookie);
    resp.addCookie(userHashCookie);

    //response.sendRedirect("HomeControllerServlet");
    RequestDispatcher dsp = req.getRequestDispatcher("HomeServlet");
    dsp.forward(req, resp);

On home Servlet I have

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for(Cookie cookie : cookies)
        {
            System.out.println("Cookie is  "+cookie.getName()+" "+cookie.getValue());
        }
    }
    doGet(req, resp);
}


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      Cookie[] cookies = req.getCookies();
        if (cookies != null) {....}

But I get no cookies apart from JSESSIONID..
Can anyone help?
I am using tomcat 8.0.18 and java 1.7.75


Source: jsp

Leave a Reply