如何在JSP中将错误消息打印到用户屏幕而不是标准输出



我想知道在用户在JSP中输入错误密码的情况下,如何向用户打印错误消息。鉴于我有表单设置和验证工作,我试图添加这一个检查,但输出被打印到标准输出ie控制台,然而,我希望它被打印到屏幕上,用户正在查看。下面是我的验证代码:

public boolean verify (String username, String password) {
        if (!password.equals("1234")) {
            System.out.println("Wrong password!n");
            return false;
        } 
        return true;        
    }

编辑:LoginProcessing.java调用上面的方法并检查布尔值(logedin),如果没有设置,我执行下面的代码,但它仍然没有打印到用户可以看到的屏幕上。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// skipping initializations for brevity
if (logedin) { 
// do stuff 
}else {
            System.out.println("Wrong password!n");
            response.sendRedirect("login.jsp");
            return;
        }
    }
编辑2:这是我的代码在login.html中的样子,我从doPost()方法中重定向到上面的代码,除了我删除了println()方法。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Using JSP</title>
</head>
<body>
<form action="login" method="post">
    Please enter your username: <input type="text" name="username"><br>
    Please enter your password:<input type="password" name="password"><br>
    <input type="submit">
</form>
<c:if test="${!loggedin}">
    Sorry. Wrong user name or password
</c:if>
</body>
</html>

在您的servlet方法中:

// check the credentials
boolean loggedIn = verify(username, password);
// store the result in a request attribute, so that the JSP can retrieve it
request.setAttribute("loggedIn", loggedIn);
// let a JSP display the result
request.getRequestDispatcher("/loginResult.jsp").forward(request, response);

在JSP中(使用JSTL)测试loggedIn请求参数的值:

<c:if test="${loggedIn}">
    Congratulations: you're now logged in.
</c:if>
<c:if test="${!loggedIn}">
    Sorry. Wrong user name or password
</c:if>

最新更新