gpt4 book ai didi

java - 从 servlet 向 html 页面发送警报

转载 作者:行者123 更新时间:2023-12-02 01:31:13 25 4
gpt4 key购买 nike

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

       String uName = request.getParameter("username");
String pass = request.getParameter("passwd");
String rpass = request.getParameter("rpasswd");
String email = request.getParameter("email");
if(uName == "" || pass == "" || rpass == "" || email == "") {
//what must i put here to send notification to html page
}

最佳答案

您可以使用 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);
}

要显示上面的消息,请在jsp页面中执行如下操作:

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

在表单中进行验证的另一种方法,您可以使用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>

希望这有帮助!

关于java - 从 servlet 向 html 页面发送警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com