问题
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?
回答1:
At login time, put the found User
object in the 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 the session.
if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
chain.doFilter(request, response); // Logged in, so just continue.
} else {
response.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 a user, just do session.removeAttribute("user")
or, more drastically, session.invalidate()
.
来源:https://stackoverflow.com/questions/3255718/jsp-deny-direct-access-to-url-by-non-logged-in-user