tags:

views:

16

answers:

1

I have a login and a user info page which is displayed after login. How can I block user info page from direct access by user? How can I implement that with session?

+2  A: 

During login, put the found User object in session.

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("secured/userpage");
} else {
    request.setAttribute("error", "Unknown username/password combo, please try again");
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

Then implement a Filter which just checks the presence of the logged-in user in session.

if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
    chain.doFilter(request, response); // Logged in, so just continue.
} else {
    resposne.sendRedirect("login"); // Not logged in, redirect to login page.
}

Map this filter on an url-pattern of /secured/* (or anything else whatever you want) and put the secured pages like the user info page in the same folder.

To logout an User, just do session.removeAttribute("user") or, more drastically, session.invalidate().

BalusC