有 Java 编程相关的问题?

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

java servlet重新源调度器在正确的位置包含html

我有一个非常基本的登录servlet

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        // get request parameters for userID and password
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username.equals("marti") && password.equals("bosch")) {
            response.sendRedirect("login_success.jsp");
        } else {
            RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    "/login.html");
            PrintWriter out = response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);
        }
    }
}

当我调用servlet时,它将从登录名中删除。html:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
    <form action="LoginServlet" method="post">
        <p>Username: <input type="text" name="username"> </p>
        <p>Password: <input type="password" name="password"> </p>
        <p><input type="submit" value="Login"></p>
    </form>
</body>
</html>

如果输入了正确的用户名和密码,浏览器将正确显示登录成功。jsp。但是,如果我没有输入正确的用户名和密码,浏览器会将未渲染的html显示为纯文本:

<font color=red>Either user name or password is wrong.</font>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
    <form action="LoginServlet" method="post">
        <p>Username: <input type="text" name="username"> </p>
        <p>Password: <input type="password" name="password"> </p>
         <p><input type="submit" value="Login"></p>
    </form>
</body>
</html>

如何使LoginServlet将消息放在正确的位置(正文标记之后)?谢谢


共 (1) 个答案

  1. # 1 楼答案

    确切地说,您需要将其作为HTML文档的内容:

    &13; 第13部分,;
    <!DOCTYPE html>
    <html>
    <head>
    <title>Login Page</title>
    </head>
    <body>
        <font color=red>Either user name or password is wrong.</font>
        <form action="LoginServlet" method="post">
            <p>Username: <input type="text" name="username"> </p>
            <p>Password: <input type="password" name="password"> </p>
             <p><input type="submit" value="Login"></p>
        </form>
    </body>
    </html>
    和#13;
    和#13;

    此外,HTML5中不推荐使用<font>标记

    编辑:

    因此,您需要sendRedirect转到包含错误消息的页面:

    response.sendRedirect("login_error.jsp");  //containing exactly the same html I posted
    

    或者修改表单JSP,使其在身份验证失败后呈现额外的错误消息。您可以通过将参数从Servlet传递到JSP来实现这一点。请参阅此thread