0

I want to show the last accessed time on the user's profile page when the user logs in again after logout. I am using HttpSession. I have three servlets

  1. Login
  2. Logout
  3. Profile

where should I use long lastTime = session.getLastAccessedTime();

here is the code:

Login

    String name = request.getParameter("name");
    String password = request.getParameter("password");

    if (password.equals("admin123")) {
        out.print("Welcome, " + name);
        HttpSession session = request.getSession();
        session.setAttribute("name", name);
    } else {
        out.print("Sorry, username or password error!");
        request.getRequestDispatcher("login.html").include(request, response);
    }

Logout

    HttpSession session = request.getSession();
    session.invalidate();

    out.print("You are successfully logged out!");

Profile

    HttpSession session = request.getSession(false);
    if (session != null) {
        String name = (String) session.getAttribute("name");
        long lastTime = session.getLastAccessedTime();
        out.print(lastTime + "last login time");
        out.print("Hello, " + name + " Welcome to Profile");
raven
  • 2,381
  • 2
  • 20
  • 44
SPGuar
  • 353
  • 6
  • 17
  • `session.getLastAccessedTime()` does not have anything to do with authentication. It is a time of the last request with the `JSESSIONID={sessionId}`. http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#getLastAccessedTime%28%29 – Pavel Horal Feb 12 '14 at 15:07
  • then how can I get last login time of the user.plz tell me. – SPGuar Feb 12 '14 at 15:09
  • You need to implement such feature yourself. Add `lastAuthenticatedOn` property on your `User` object and update it at the end of the authentication. – Pavel Horal Feb 12 '14 at 15:10

1 Answers1

0

do one store store in db when user logouts and use it next time.This is good method. I don't think other methods will work if server restarts .Store in db when user session ends or as per your requirement.If you want to user HttpSession listener have a look http://www.mkyong.com/servlet/a-simple-httpsessionlistener-example-active-sessions-counter/

Dhruv Pal
  • 849
  • 2
  • 10
  • 25