How to create session for login and logout in java

Madhavi Talla picture Madhavi Talla · Oct 21, 2014 · Viewed 26.9k times · Source

This is the code that I have written in login page

HttpSession session = request.getSession(true);
session.setAttribute("name", user1);        
String nme=(String) session.getAttribute("name");

And, This is the code for logout.jsp

<% request.getSession().invalidate();

OR

if(session!=null){
   session=null;
}

OR

 request.getSession().setAttribute("name", null); //it just assigns null to attribute

 response.sendRedirect("login.jsp");
 %>

session is creating, But after logout button is working.... I want that back button should not work.

Answer

Shishir Kumar picture Shishir Kumar · Oct 21, 2014

To logout or invalidate from the current session, you have the correct code in place, as below.

request.getSession().invalidate();

Now, after you hit the back button of the browser, it is loading the page from the cache. So in order to take care of this situation you can do below 2 things.

  1. Manipulate the browser history using HTML 5's History API so that when you click the back button it goes to the desired location as you manipulate it.

  2. Suggest user to close the page, as general secured websites do after successful session logout, like bank websites & financial websites.

Alternatively, you can write & configure an interceptor class in servlet container/server end to manipulate the cache by adding below parameters in the response.

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

Hope this helps you out.