22

我有一个用于登录的过滤器。它对“用户名”和“密码”字段执行文本检查。当且仅当文本检查正确完成时,请求才会发送到 Servlet。后者执行必须与数据库交互的控制。这个链条正确吗?

4

1 回答 1

53

前言:我猜您使用的是本地登录而不是容器管理的登录。对于所有方式,请参阅如何处理数据库中用户的身份验证/授权?


过滤器(拦截器)不应检查用户名/密码组合的有效性。这是 servlet(控制器)的职责。

过滤器应该只检查用户是否登录(通常只检查会话属性的存在),然后继续请求或通过重定向回登录页面来阻止它。

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURI = request.getContextPath() + "/login";

        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }

    // ...
}

servlet 应该收集提交的数据,User在数据库中找到关联的数据,如果找到,则将其存储为会话属性,然后重定向到主页,否则重新显示带有验证错误的表单。

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String, String> messages = new HashMap<String, String>();

        if (username == null || username.isEmpty()) {
            messages.put("username", "Please enter username");
        }

        if (password == null || password.isEmpty()) {
            messages.put("password", "Please enter password");
        }

        if (messages.isEmpty()) {
            User user = userService.find(username, password);

            if (user != null) {
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/home");
                return;
            } else {
                messages.put("login", "Unknown login, please try again");
            }  
        }

        request.setAttribute("messages", messages);
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

}

也可以看看:

于 2012-11-07T19:44:07.803 回答