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

时间:2014-08-22 15:35:13

标签: java jsp error-handling

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

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>

1 个答案:

答案 0 :(得分:1)

在你的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>