-4

I have following code segment in my servlet. Here, for some reason, I can not hold the session for the same user after creation of one session.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("text/html");
PrintWriter writer =  response.getWriter();
String userName = request.getParameter("userName");
HttpSession session = request.getSession();

if (userName != "" && userName != null) {
    session.setAttribute("savedUserName", userName);
}

writer.println("Request parameter has user name as : " + userName + "<br />");
writer.println("Request session has user name as : " + (String) session.getAttribute("savedUserName") + "<br />");
    }
Shahjalal
  • 1,163
  • 7
  • 21
  • 38

1 Answers1

1

On what basis are you implying that the session is not working? The only scenario that might not work is when you have not supplied userName in which case the it will be null and session will never be created as your below code is testing the condition in wrong order and the equality check should use equals() and not !=

if (userName != "" && userName != null) {
    session.setAttribute("savedUserName", userName);
}

It should be changed to

if (userName != null && !userName.equals("")) {
    session.setAttribute("savedUserName", userName);
}
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327