黑马程序员
案例–校验用户是否存在
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<h3>失去焦点对输入框内容进行校验</h3>
<script>
$(function () {
$("#userName").blur(function () {
var username = $(this).val();
//{userExist:true,mag:'用户名存在'}
$.get("userRegisterServlet", {userName: username}, function (data) {
if (data.userExist) {
$("#msgShow").css("color","red");
$("#msgShow").html(data.msg);
} else {
$("#msgShow").css("color","green");
$("#msgShow").html(data.msg);
}
}, "json")
});
})
</script>
<input type="text" id="userName" name="userName" placeholder="userName"><span id="msgShow"></span><br>
<input type="password" name="passWord" placeholder="passWord">
<input type="submit" value="提交">
</body>
</html>
package cn.itcast.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
@WebServlet("/userRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String userName = request.getParameter("userName");
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> booleanStringHashMap = new HashMap<>();
if (userName.equals("tom")) {
booleanStringHashMap.put("userExist", true);
booleanStringHashMap.put("msg", "用户名已存在,请更换!");
} else {
booleanStringHashMap.put("userExist", false);
booleanStringHashMap.put("msg", "用户名合法");
}
mapper.writeValue(response.getWriter(),booleanStringHashMap);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}