1

I am new to Servlets and sessions.

I am building a website using Servlets and JSP's.I am using Http connection.

I am using Sessions,After login into my website session is created ,When i click the browser back button again and again ,i can go to the login screen and again on clicking the browser forward option i can enter into the website without any issues.

My expectation is When the browser goes to the login screen,the session should be expired and it should again ask for new password.

Is there anyway i can do it with this http connection.

VijayManohar7
  • 123
  • 2
  • 11

2 Answers2

1

You can invalidate the session in your show login servlet:

....
HttpSession session = request.getSession(false);
if (session != null) {
    session.invalidate();
}

This solution works both for first visit and return visits.


If you want to invalidate the session only if this is not the first visit you can do that:

In login servlet

HttpSession session = request.getSession(false);
session.setAttribute("loggedUser", loggedUser);

In show login servlet

HttpSession session = request.getSession(false);
if (session != null) {
    if (session.getAttribute("loggedUser") != null) {
        session.invalidate();
    }
}

Note if you use a standard login process you can use instead in the show login method

HttpSession session = request.getSession(false);
if (session != null) {
    if (request.getRemoteUser() != null) {
        session.invalidate();
    }
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • 1
    is there anyway i can get the browser action,through any listener ,so that i can make a check based on that – VijayManohar7 Nov 13 '15 at 08:29
  • I will explain my functionality requirement,during login i will create a Session. and then i ll maintain the session until he logouts.If he uses the back option(in browser) and comes back to the login screen.I need to invalidate the session(as you suggested).But i am not able to differntiate between browser back to login screen or first time Viewing login screen . – VijayManohar7 Nov 13 '15 at 08:35
0

Some ideas would be:

Check on your login.page, before you do anything other, if your mySession != null. You can get your session like HttpSession mySession= request.getSession(false); If your session is not null, your user already logged in once. In this case you can invalidate your session mySession.invalidate();

Overall it should looke like that:

   HttpSession mySession = request.getSession(false);
   if (mySession != null) 
   {
       mySession .invalidate();
   }

Another problem could be the browser chaching your page.

An idea how to disable this in the clients browser can be found in this question.

A third way could be using javascript. You could add a listener on browser back. An question with anser is already avalibale here.

Hope that helps

Community
  • 1
  • 1
Felix Gerber
  • 1,615
  • 3
  • 30
  • 40