I have no idea why my session.getAttribute("user") return not null but attribute value retun null after few minutes, it might due to session time out but why only the attribute value return null but other session still there even session.getAttribute("user") return not null.
This is my web page flow, User Login
LoginServlet
User s = new User();
s.retriveuser();
session.setAttribute("balance", s.getBalance());
session.setAttribute("username", s.getUsername());
session.setAttribute("user", s);
My Profile
User user = new User();
if (session.getAttribute("user") == null) {
response.sendRedirect("login.jsp");
} else {
user = (model.User) session.getAttribute("user");
}
<tr>
<th>Gender:</th>
<td><%=user.getGender()%></td>
</tr>
<tr>
<th>Name:</th>
<td><%=user.getName()%></td>
</tr>
It can display after the user login everything work fine, after few minutes the gender name ... will display null instead of redirect to login page. And my balance and username session still there. Before setting else user = (User) session.getAttribute("user"); I was using
<jsp:useBean id="user" class="model.User" scope="session" />
Ok, so attribute "user" becomes null.
Que?? So attribute "user" is not null??
There are only two possibilities for changing session attributes:
Extra Note A: from javadoc for
HttpServletResponse.sendRedirect
: After using this method, the response should be considered to be committed and should not be written to. Your code above violates this.Extra Note B:
You just populated it with a rubbish new, empty user object. Avoid that - it's a bug waiting to happen. Only set variables to useful/valid values. :)
What have you been using inside the bean code? Are you sure you have made an empty constructor, getters, setters, that the java class implements Serializable?Then, on the jsp page it's better that you use
<jsp:setProperty name="the_same_you_used_in_bean_id" property="*"/>
. If you want some more info about the bean structire, let me know!I don't readily have access to test this out. But I am guessing the
user
object is not created in the session, hence does not get set tonull
.Should solve your problem.
Edit Also, simply printing
user.Gender()
will returnNull
in this case, so you're better off printing it straight from the session variable.