Antoros
Antoros

Reputation: 3

Servlet not saving variables to session

This is the small part that I'm missing, I got the rest of the queries ready but none of them works because when I try to save an Attribute to a servlet, it doesn't work.

    // used a form in a JSP
    // retrieved the data from the session same as
    // accion=request.getParameter("accion"); no errors there
    // used to query sql server to check if exist

    if(usuario!=null){

            // i dont know why but here is the problem

            HttpSession session= request.getSession(); // tried with (false)
            Usuario user =usuario;                     // same error
            session.setAttribute("usu",user);

            //Retrieval test
            Usuario test=(Usuario)request.getAttribute("usu");

            if(test!=null){
                    out.println("User != null");
            }else{
                    out.println("User == null");
            }

            //output is "User == null" and cant figure out why

            //response.sendRedirect("./intranet/adminLogin.jsp?logged=1");
    }

And if in the JSP i check for a session (after redirect) it doenst have one neither

    if(request.getSession(false)==null){
            out.println("#info there is no session <br />");
    }else{
            out.println("#info there is a session <br />");
    }
    // 

I need to sort this out so I can't fix everything that need sessions.

Upvotes: 0

Views: 1413

Answers (1)

EJK
EJK

Reputation: 12534

Your retrieval test code is getting the attribute from the request. That is a different object from the session.

Replace:

    Usuario test=(Usuario)request.getAttribute("usu");

With:

    Usuario test=(Usuario)session.getAttribute("usu");

Upvotes: 3

Related Questions