Reputation: 19
I have 3 JSP files : login.jsp :
...
<body>
<font face="tahoma" size="2">
<form action="log" METHOD="POST">
<p>login:</p>
<input type="text" name=login value="person" />
<p>password:</p>
<input type="password" name=password value="" />
<input type="submit" name="next" value="OK" />
</font>
</body>
.....
logout.jsp
...
<body>
<font face="tahoma" size="2">
session id : ${sessionScope.sesId}</p>
user : ${sessionScope.userName}</p>
<h3>Logout page</h3>
<form action="logout" METHOD="POST">
<input type="submit" name="in" value="log in again" />
</font>
</body>
....
logged.jsp
....
....
and servlet for login.jsp
...
HttpSession ses = request.getSession(false);
if (ses == null) {
ses = request.getSession();
ses.setAttribute("userName", login);
ses.setAttribute("sesId", ses.getId());
request.getRequestDispatcher("/logged.jsp").forward(request,response);
}else {
ses.invalidate();
request.getRequestDispatcher("/logout.jsp").forward(request,response);
}
...
NetBeansIDE 7.4 Tomcat on localhost Windows 7
When I start project (Run / Run Project) it allways redirect to logout.jsp . sesId and userName are null (or empty ?)
Why ?
Upvotes: 1
Views: 646
Reputation: 160191
JSPs create a session unless explicitly configured not to.
Instead of checking for the existence of a session check for a value in the session.
Upvotes: 2
Reputation: 8659
The session object itself is not going to be null unless maybe the user has cookies disabled (even then I don't think it would be null). You need to check an attribute for null instead.
String username = (String)ses.getAttribute("userName");
if(username == null)
Upvotes: 1