Skip to main content
 首页 » 编程设计

用于登录的身份验证过滤器和 servlet

2024年02月06日9xxx_UU

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

请您参考如下方法:

前言:我猜您正在使用本地登录而不是容器管理登录。所有方式请参见How to handle authentication/authorization with users in a database?

<小时 />

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

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

@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,如果找到,则将其存储为 session 属性,然后重定向到主页,否则重新显示带有验证错误的表单。

@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); 
    } 
 
} 

另请参阅: