简介
利用AJAX的异步更新,实现注册用户时,焦点离开用户名输入框时,系统监测数据库中是否已有该用户名的功能,这里并没有直接访问数据库,而是以假数据的形式写了html和servlet页面的部分功能。
代码部分
<head>
<meta charset="UTF-8">
<title>注册校验</title>
<style>
#div1{
margin: 150px auto;
padding: 50px;
background-color: beige;
}
</style>
<script src="static/js/jquery-3.2.1.min.js"></script>
<script>
$(function () {
//给用户名输入框绑定 失去焦点事件blur
$("#username").blur(function () {
//获取文本框的值
var username = $(this).val();
//发送ajax请求。期望返回数据:{"userExsit":true,"msg":"用户名已存在"};{"userExsit":false,"msg":"该用户名可用"}
$.get("findUsernameServlet",{username:username},
function (data) {
//获取s_username元素
var s_username = $("#s_username");
//判断userExsit值
if (data.userExsit){
//用户名存在
s_username.css("color","red");
s_username.html(data.msg);
}else {
//用户名不存在
s_username.css("color","green");
s_username.html(data.msg);
}
},"json");
});
});
</script>
</head>
<body>
<div id="div1">
<form>
<input type="text" name="username" id="username" placeholder="请输入用户名">
<span id="s_username"></span><br>
<input type="password" name="password" id="password" placeholder="请输入密码"><br><br>
<input type="submit" value="注册">
</form>
</div>
</body>
@WebServlet(urlPatterns = "/findUsernameServlet")
public class findUsernameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//1. 获取页面传来的username
String username = request.getParameter("username");
//2. 调用service层,判断用户名是否存在
Map<String,Object> map = new HashMap<String, Object>();//定义一个map返回处理结果的键值对
String exsitUsername = "Tom";//假设存在一个Tom
if (username.equals(exsitUsername)){
//用户名存在
map.put("userExsit",true);
map.put("msg","用户名已存在");
}else {
//用户名不存在
map.put("userExsit",false);
map.put("msg","该用户名可用");
}
//将map转换为json,并传递给客户端
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(),map);
}
}