views:

49

answers:

1

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 username and userid in session object and use it in another page but it is returning null value.

A: 

Several causes:

  1. You've put it in the session the wrong way (should be done by session.setAttribute(key, value)).
  2. The other page is in a different domain/context (and thus doesn't use the same session).
  3. Something has invalidated the session (e.g. session.invalidate()).
  4. The client doesn't support cookies and you haven't added URL rewriting support.
  5. 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.

BalusC