html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-3.7.0.js"></script>
<script>
$(function () {
var username_flag = false;
var password_flag = false;
//用户输入框失去焦点
$("[name=username]").blur(function () {
//获取输入框的值
var usernameValue = $(this).val();
//判空
if (usernameValue == null || usernameValue == "") {
$("#span1").text("账号不能为空");
} else {
//判长度
if (usernameValue.length < 5) {
$("#span1").text("账号不能少于5位");
} else {
//判断账号的唯一性
$.get("LoginServlet",{"username":usernameValue},function (date) {
console.log(date)
if (date) {
$("#span1").text("√");
$("#span1").css("color","green");
username_flag = true;
} else {
$("#span1").text("此账号已被注册过!请重新输入");
}
},"json");
}
}
});
//密码输入框失去焦点
$("[name=password]").blur(function () {
var passwordValue = $(this).val();
//判空
if (passwordValue == null || passwordValue == "") {
$("#span2").text("密码不能为空");
} else {
//判长度
if (passwordValue.length < 5) {
$("#span2").text("密码不能少于5位");
} else {
//判内容
var rule = /^\d*$/;
if (rule.test(passwordValue)) {
$("#span2").text("密码不能是纯数字");
} else {
$("#span2").text("√");
$("#span2").css("color","green");
password_flag = true;
}
}
}
});
$("form").submit(function(){
if(username_flag && password_flag){
alert("提交成功")
return true;
}else{
alert("数据有误!")
return false;
}
});
});
</script>
</head>
<body>
<form>
用户名:<input type="text" name="username"><span id="span1" style="color: red"></span><br>
密码:<input type="password" name="password"><span id="span2" style="color: red"></span><br>
<input type="submit" value="登录">
</form>
</body>
</html>
java
package com.etime.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取名字
String username = request.getParameter("username");
boolean flag;
//假设数据库只有admin用户
if ("admin".equals(username)){
//用户已经存在
flag = false;
} else {
//用户不存在
flag = true;
}
PrintWriter writer = response.getWriter();
writer.print(flag);
writer.close();
}
}