Wu Zijan
Wu Zijan

Reputation: 433

jsp directly jumps to html rather than through servlet

I made an web app which has the login and logout functions.

The first time I login and logout seems normal.

But when I change another account and repeat above operations,

the logout operation directly jumps to the index.html rather than through

the LogoutServlet.java. So the session is still valid.

Do you know the reason?

I'll be appreciated that you tell me the reason.

There are my key codes as following.

LoginServlet.java

HttpSession session = request.getSession(false);
        if(session!=null) 
            session.setAttribute("LoginUser", user);
        request.getRequestDispatcher("/WEB-INF/jsp/home.jsp")
                   .forward(request, response);

home.jsp

<a href="Logout.action">Logout</a>

LogoutServlet.java

@WebServlet("/Logout.action")
protected void doGet(...) {
    HttpSession session = request.getSession(false);
    if(session!=null) {
        session.removeAttribute("LoginUser");
        session.invalidate();
    }
    request.getRequestDispatcher("/index.html").forward(request, response);
}

You can try it on my website. http://anwuli.cn/HelloWorld

Provided 2 test accounts.

format: username&password

First: admin&123456

Second: anpeng&123456

Upvotes: 1

Views: 51

Answers (2)

Jonathan Laliberte
Jonathan Laliberte

Reputation: 2725

As the previous answer has mentioned. You are not creating a new session if one doesn't exist when you check if there is a session with:

request.getSession(false)

So the if block is not true when a logged in account tries to logout:

 if(session!=null) {
        session.removeAttribute("LoginUser");
        session.invalidate(); // this code never runs...
    }

You need to either use:

HttpSession session = (request.getSession());

or

HttpSession session =  request.getSession(true)

Also, a session is created anytime a new user connects to your website (even if they have not logged in.)

So you need to check if the attribute is null like this:

 if(null == session.getAttribute("LoginUser")){  
         //no logged in user
         RequestDispatcher rd=request.getRequestDispatcher("login.jsp"); //replace with your login page  
           rd.forward(request,response);    
           return;
    }else{
         //user attribute is not null so logout
        session.invalidate();
     }

Upvotes: 1

marojbor
marojbor

Reputation: 311

You are using HttpSession session = request.getSession(false); so you don't create any new session in the LoginServlet.java.

Where do you create your first session ?

Upvotes: 1

Related Questions