servlet如何实现 客户输入空的帐号密码提交 html下方显示不能为空的功能 不借助JavaScript实现
可以在Servlet中进行验证,如果客户端提交的账号密码为空,则在返回的HTML页面中输出提示信息。具体实现步骤如下:
-
在HTML页面中添加一个表单,并设置提交的URL为Servlet的地址。
-
在Servlet中获取表单提交的账号密码信息。
-
判断账号密码是否为空,如果为空,则设置一个标志位。
-
返回HTML页面时,判断标志位是否为真,如果为真,则在页面下方输出提示信息。
下面是一个简单的示例代码:
HTML页面:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Servlet:
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean isEmpty = false;
if (username == null || username.isEmpty()) {
isEmpty = true;
}
if (password == null || password.isEmpty()) {
isEmpty = true;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Login Results</title></head>");
out.println("<body>");
if (isEmpty) {
out.println("<p style='color:red'>Username and password cannot be empty.</p>");
} else {
// do login validation
}
out.println("</body></html>");
}
}
在这个示例中,如果客户端提交的账号密码为空,就会在页面下方输出一个红色的提示信息。如果账号密码不为空,则可以进行登录验证操作。注意,在实际开发中,需要对账号密码进行更加严格的验证,以确保应用程序的安全性
原文地址: http://www.cveoy.top/t/topic/hsx3 著作权归作者所有。请勿转载和采集!