JSP中 用户输入了空表单提交 如何利用getAttribute方法提示输入了空字符
可以通过以下步骤来实现:
-
在jsp页面中设置表单,并在表单提交时调用一个servlet处理提交请求。
-
在servlet中获取表单参数,判断是否为空。
-
如果为空,利用setAttribute方法将一个错误提示信息存储到request中。
-
返回原始jsp页面,并在jsp页面中使用getAttribute方法获取错误提示信息,并将其展示给用户。
示例代码如下:
在jsp页面中设置表单:
<form action="processForm" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Submit">
</form>
在servlet中获取表单参数并判断:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null || username.equals("") || password == null || password.equals("")) {
request.setAttribute("error", "Please enter both username and password.");
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
else {
// process form data
}
}
在jsp页面中使用getAttribute方法获取错误提示信息并展示:
<% String error = (String)request.getAttribute("error"); %>
<% if (error != null) { %>
<div class="error"><%= error %></div>
<% } %>
``
原文地址: https://www.cveoy.top/t/topic/hsxl 著作权归作者所有。请勿转载和采集!