JSP deny direct access to URL by non-logged in use

2019-04-14 01:14发布

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条回答
不美不萌又怎样
2楼-- · 2019-04-14 02:11

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().

查看更多
登录 后发表回答