页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
</head>
<body>
<script>
function checkUser() {
$.post({
url:"${pageContext.request.contextPath}/user/registerAjaxCheck",
data: {'name':$('#username').val()},
success:function (data) {
if (data.toString()==='OK'){
$('#info').css("color","blue");
$('#info').html("用户名可以注册");
}else if (data.toString()==='null'){
$('#info').css("color","red");
$('#info').html("用户名不能为空");
} else {
$('#info').css("color","red");
$('#info').html("用户名已存在");
}
}
});
}
</script>
<form action="${pageContext.request.contextPath}/user/insertUser" method="post" class="form-horizontal">
<div style="height: 20%"></div>
<div style="width: 80%;align-content: center" >
<div style="width: 100%;align-content: center;height: 30px;">
<span id="info" style="margin-left: 20%">${msg2}</span>
</div>
<div class="form-group" >
<label class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input onblur="checkUser()"
id="username"
style="width: 30%" type="text" class="form-control" placeholder="输入用户名" name="userName">
</div>
</div>
<div style="width: 100%;align-content: center;height: 30px;">
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input style="width: 30%"type="password" class="form-control" placeholder="输入密码" name="password">
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-2 col-sm-10" >
<button type="submit" class="btn btn-default">注册</button>
</div>
</div>
</div>
</form>
</body>
</html>
Controller
注意返回的是一个json字符串,ajax是前后端分离的核心。
//Ajax异步验证用户名
@RequestMapping("/registerAjaxCheck")
@ResponseBody
public String registerAjaxCheck(String name , HttpServletResponse response){
System.out.println(name);
User user = userService.checkUser(name);
String msg = "";
if (name==null||name.equals("")){
msg = "null";
}else if (user==null){
msg = "OK";
}
System.out.println(msg);
return msg;
}