有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

servlets HttpServletRequest#login()在Java中不起作用

j_security_check似乎不足以让我执行登录过程。因此,我没有将表单提交给j_security_check,而是创建了自己的servlet,并以编程方式尝试登录。这是可行的,但我无法重定向到我的受限资源。谁能告诉我有什么问题吗?这是我的servlet的processRequest方法:-

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String strUsername = request.getParameter("txtusername");
            String strPassword = request.getParameter("txtpassword");
            if(strUsername == null || strPassword == null || strUsername.equals("") || strPassword.equals(""))
                throw new Exception("Username and/or password missing.");
            request.login(strUsername, strPassword);
            System.out.println("Login succeeded!!");

            if(request.isUserInRole(ROLES.ADMIN.getValue())){//enum
                System.out.println("Found in Admin Role");
                response.sendRedirect("/app/Admin/home.jsf");

            }
            else if (request.isUserInRole(ROLES.GENERAL.getValue()))
                response.sendRedirect("/app/Common/index.jsf");
            else //guard
                throw new Exception("No role for user " + request.getRemoteUser());


        }catch(Exception ex){
            //patch work why there needs to be blogger here?
            System.out.println("Invalid username and/or password!!");
            response.sendRedirect("/app/Common/index.jsf");
        }finally {
            out.close();
        }
    } 

一切正常,我甚至可以看到消息“在管理员角色中找到”,但问题是,即使在验证后,我也无法将请求重定向到其他页面


共 (2) 个答案

  1. # 1 楼答案

    去掉那些线,它们不属于那里:

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
    

            out.close();
    

    如果关闭OutputStream,则无法进行重定向。实际上,您应该在服务器日志中看到IllegalStateException: Response already committed