首页 > 解决方案 > 在收到来自 servlet 的响应之前,JSP 不显示任何文本

问题描述

我正在尝试使用 servlet 检索从 servlet 返回的数据以显示在页面上。我的问题是我的 JSP 代码片段有效,但在它收到来自服务器的响应之前,它在屏幕上显示来自 request.getAttribute 代码的 null 。

这是我的代码

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>

    <title>GameAlytics Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel ="stylesheet" href="styles.css">

</head>
<body>


 <div id="navbar">
                <div id="logo">
                <img SRC="logo.png" ALT="Unable to load image" WIDTH=150 HEIGHT=90>
            </div>
                <div id="navbar-right">
                    <a class="active" href="index.html">Home</a>
                    <a href="Login.html">Login</a> 
                    <a href="ViewData.html">View Data</a>
                    <a href="Contact.html">Contact</a>
                    <a href="About.html">About</a>
                </div>
            </div>

    <form action="Login" method="GET">
          <div class="imgcontainer">
            <img src="images/avatar.jpg" alt="Avatar" class="avatar">
          </div>

          <div class="container">
            <label for="username"><b>Username</b></label>
            <input type="text" placeholder="Enter Username" name="username" id="username"  required>

            <label for="psw"><b>Password</b></label>
            <input type="password" placeholder="Enter Password" name="password" id="password" required>

            <button>Login as administrator</button>
          </div>
        </form>
        <p style="color:red; font-size: 20px;"><%=request.getAttribute("errorMessage")%></p>
        <div id="footer">
          <h2>Copyright of GameAlytics 2019</h2>
        </div>
        </body>
        </html>

小服务程序:

 //if details entered are correct, take user to system info page
          if(enteredUsername.equals(dbUsername)&&enteredPassword.equals(dbPassword)){

             response.sendRedirect("ViewData.html");     
          }

          ///if details entered are incorrect, user remains on login page
          else{

               request.setAttribute("errorMessage", "Invalid user or password");
               request.getRequestDispatcher("test.jsp").forward(request, response); 
          }

        }//try end

真的,我只是在寻找一种方法来隐藏 null 并且只在结果到达时显示结果

标签: jspservletsrequest

解决方案


您可以检查该值是否null如下所示:

//here we check if  the errorMessage is not null
<% if(request.getAttribute("errorMessage") !=null){ %>
  <p style="color:red; font-size: 20px;">
<%=request.getAttribute("errorMessage"); %>
 </p>
<% } %>

推荐阅读