parsecer
parsecer

Reputation: 5106

Java servlet, session: null session gets created, can't invalidate it

I have a form that takes a username and passes it to LoginServlet.java which in turn:

  1. If there's no session: creates a session for that username and forwards the request to LoginResultView.jsp which dispays a "Successful login, %username%" message
  2. If there already is a session, prints out "wow..." and invalidates the old session:

form:

<form method="POST" action="LoginResult.do">
  <div>
     <label id="username-label" for="usr">username:</label><br/><br/>
     <input type="text"
            value="Enter a username"
            class="form-control form-input-field form- username-input-field default"
            id = "form-username-input-field" name="login-username"
     >                        
  </div>

  <button class="btn btn-success" type="submit">Sign up</button>
</form>

servlet:

public class LoginServlet extends HttpServlet {
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws
                                                                        IOException, ServletException {
        String username = request.getParameter("login-username");

        response.setContentType("text/html");
        HttpSession session = request.getSession(false);  

        if (session==null)  {
                session = request.getSession(true);  
                session.setAttribute("loginUsername", username);
                RequestDispatcher view= request.getRequestDispatcher("view/LoginResultView.jsp");
                view.forward(request, response);
        }
        else  {
                response.getWriter().println(
                        "wow, how are you here, " + 
                        session.getAttribute("loginUsername"));
                response.getWriter().println(
                        session.getMaxInactiveInterval());
                session.invalidate();
        }

    }
}

I also have a navbar that, if there's no session, displays two buttons: Log In and Sign Up and if there's a session, it displays a loginUsername attribute, associated with that session:

<% HttpSession session2 = request.getSession(false);
     if (session.getAttribute("loginUsername") != null) {
%>
          <div class="dropdown navbar-link">
              <button class="btn btn-secondary dropdown-toggle"
                     type="button" id="dropdownMenuButton"
                     data-toggle="dropdown"
                     aria-haspopup="true" aria-expanded="false">
                 <a href="${pageContext.request.contextPath}/Login.jsp">                              
                   <%out.println(session2.getAttribute("loginUsername"));%>
                 </a>
              </button>

              <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                 <a class="dropdown-item"
                                     href="${pageContext.request.contextPath}">Profile</a>
                 <a class="dropdown-item"
                     href="#">Link2</a>
                 <a class="dropdown-item"
                  href="${pageContext.request.contextPath}/LogoutResult.do">                                
                      Log out
                  </a>
              </div>
     </div>

        <%
             }
             else  {
         %>
             <a href="${pageContext.request.contextPath}/Login.jsp"
                class="btn btn-info" role="button">Log in
             </a>

             <a href="${pageContext.request.contextPath}/Login.jsp"
                               class="btn btn-info" role="button">Sign up
             </a>


        <%
             }
        %>

The problem is this: even if there's seemingly no session (it's the two Log in and Sign Up buttons up there) when I fill up the form and send it to LoginServlet I still get a message wow, how are you here, null 120 (120 is a session-timeout, specified in web.xml file). Then, I can only send the form's data by sending the same POST data again (I click the round Renew button and click OK on save previous data). Only after that do I get the LogoutResultView.jsp page.

Why does this happen? Where does this null session comes from? How do I fix it?

Upvotes: 1

Views: 944

Answers (1)

gsl
gsl

Reputation: 676

The session you get is not null. Otherwise you would get an NPE.

You need to put the session="false" attribute into the <%@page%> directive of your Navbar JSP. Otherwise, a session is immediately generated when the JSP is first visited. For example:`

<%@ page language="java" contentType="text/html; charset="ISO-8859-1"
         pageEncoding="ISO-8859-1" session="false"
         import="java.util.*" %>`

The session attribute defaults to true, so if you don't have it explicitely, a session will always be created in the background if none exists.

So, if (session.getAttribute("loginUsername") != null) does not generate a NPE, as it usually would.

If you put session="false" into your page directive, the check must be if ( session == null ). That's want you want.

Upvotes: 2

Related Questions