ChrisSherwood
ChrisSherwood

Reputation: 347

Getting a JSP servlet session, returns a null value

I am using jsp/servlets for a basic ajax application. I am setting a session with a servlet, but i am getting a null returned. My code snippets as follow:

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws  ServletException, IOException {

    String name=null;
    String sessionStrSet = null;


    if(request.getParameter("session").toString().equals("setSession")){

         name = request.getParameter("user");

         HttpSession session = request.getSession(true);
         session.setAttribute("sessionPw", name);
         sessionStrSet = session.getAttribute("sessionPw").toString();

         response.setContentType("text/plain");  
         response.setCharacterEncoding("UTF-8"); 
         response.getWriter().write(sessionStrSet + " " + "data write");

    }

    if(request.getParameter("session").toString().equals("getSession")){
        //how do i retrieve the session data here?
        response.setContentType("text/plain");  
        response.setCharacterEncoding("UTF-8"); 
        response.getWriter().write(sessionStrSet + "get session");
    }


}

The ajax works fine it is just the session retrieving that seems to be an issue. I can pull the data once its been set in the first if(). But when I do another post request it comes back as null. Do I need another HttpSession? Any help much appreciated, I am a PHP dev not JSP so its very new to me!

Upvotes: 0

Views: 3478

Answers (1)

Łukasz Rzeszotarski
Łukasz Rzeszotarski

Reputation: 6140

Do you really need separate ifs?

getSession(true) returns current session or create new if there is no current.

See at the documentation http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29

Upvotes: 1

Related Questions