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!
ifblock, which is mutually exclusive from the firstifblock, you need to callrequest.getSession(false)to get the session that was populated by the earlier POST. Think of the session as a global area that can be shared across requests. - jalynn2