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

蓝咒 提交于 2020-01-01 17:11:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!