0
    HttpSession session = request.getSession();
    User user = (User)session.getAttribute("user");
    if(user == null){
        response.sendRedirect("login.jsp");
    }
    System.out.println(user);

I am writing this code in a servlet and deploying it in Tomcat Server. After the session expires, session is automatically created but the "user" attribute becomes null. But the page is not redirected to "login.jsp" and "null" gets printed on the console.

I am using MyEclipse IDE.

Deepanshu
  • 291
  • 1
  • 3
  • 8

1 Answers1

0

That's because the call to getSession() without a boolean parameter will create another session.

Do this: HttpSession session = request.getSession(false);

Also, make sure you place this snippet before any other headers are sent to avoid confusing the browser.

However, for a more comprehensive solution, see @BalusC's comment

stan
  • 4,885
  • 5
  • 49
  • 72