从servlet发送警报到html页面

时间:2019-05-07 19:26:59

标签: java servlets

我正在尝试使用Java servlet创建注册页面。如何在html页面上通知表单中的空字段?这是我的代码的一部分

sed -n '10,+10p' a_file

2 个答案:

答案 0 :(得分:3)

您可以使用 request.getAttribute() request.setAttribute() 例如:

 String uName = request.getParameter("username");
       String pass = request.getParameter("passwd");
       String rpass = request.getParameter("rpasswd");
       String email = request.getParameter("email");
       if(uName == null|| pass == null || rpass == null || email == null) {
       //here you can set attribute like any error message
       request.setAttribute("error", "Please fill all fields in form");
        request.getRequestDispatcher("yourjsppage").forward(request,response); 
       }

要显示在message上方,请在jsp页面中执行以下操作:

//this line will print whatever is in error :  Please fill all fields in form
<p class="text-center" style="color: green">${error}</p>

使用validation属性的另一种形式,可以使用required属性,如下所示:

<form  method="post" action=""> 

 <label for="userid">Name:</label>  
   <input type="text" name="username" required  /><br/>
<label for="passid">Email:</label> 
<input type="text" name="email"  required /> 
<br/>
<input type="submit"  value="Signup"/>

</form>

希望这会有所帮助!

答案 1 :(得分:0)

   String uName = request.getParameter("username");
   String pass = request.getParameter("passwd");
   String rpass = request.getParameter("rpasswd");
   String email = request.getParameter("email");
    HttpSession session=request.getSession()
   if(uName == null|| pass == null || rpass == null || email == null) {
   //Here you can set session attribute like any error message
   session.setAttribute("error", "Please fill all fields in form");
    request.getRequestDispatcher("yourPage.jsp").forward(request,response); 

然后将这行代码添加到您的jspPage

<p>${error}</p>

最后不要忘记取消会话

session.setAttribute('error','');