session object returning null
i have created a login page for my project "student information system" which contain text fields username,userid and password.i tried to store the value of use开发者_如何学JAVArname and userid in session object and use it in another page but it is returning null value.
Several causes:
- You've put it in the session the wrong way (should be done by
session.setAttribute(key, value)
). - The other page is in a different domain/context (and thus doesn't use the same session).
- Something has invalidated the session (e.g.
session.invalidate()
). - The client doesn't support cookies and you haven't added URL rewriting support.
- You're accessing it in the session the wrong way (should be done by
session.getAttribute(key)
or${key}
).
The following login.jsp
example..
<form action="login" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
<span class="error">${error}</span>
</form>
<p>Debug info: your current session ID is ${pageContext.session.id}</p>
..with a servlet mapped on /login
which has basically the following in doPost()
..
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(response.encodeRedirectURL("home.jsp"));
} else {
request.setAttribute("error", "Unknown login, try again");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
..and a home.jsp
which look like this..
<p>Welcome, ${user.name}!</p>
<p>Debug info: your current session ID is ${pageContext.session.id}</p>
..should just work.
Ensure that the session ID is the same in both pages. For debugging purposes you can view it by ${pageContext.session.id}
as shown in the above JSP code snippets. If it is the same and the User
object is still not there, then the problem lies somewhere else.
精彩评论