简体   繁体   中英

How to create session for login and logout in java

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.

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.

just remove the attribute from session, and check if it exists.....

request.getSession.removeAttribute("name")

and check like:

if(request.getSession.getAttribute("name")==null){

}

Your problem is not with the session, as it will not be used in page that has already been loaded and simply loaded from the cache (back button functionality)

Consider utilizing localtion.href.replace in you client code.

localtion.href.replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM