本文实例为大家分享了JavaWeb实现注册用户名检测的具体代码,供大家参考,具体内容如下
案例说明实现一个可以异步获取用户名是否被注册的小案例。如:
1.编写Html与js:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="/jqueryWeb/js/jquery-3.3.1.js"></script>
<script>
$(function () {
$("#username").on("blur",function () {
$.ajax({
url : "/jqueryWeb/checkUsername",
data : "username="+$("#username").val(),
dataType : "json" ,
type : "post",
success : function (data) {
if(data.code == 1){
$("#msg").css("color","green");
}else {
$("#msg").css("color","red");
}
$("#msg").css("display","inline")
$("#msg").text(data.msg);
},
error: function () {
alert("服务器发生了错误");
}
})
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="username" name="username" type="text" placeholder="注册用户名"/><br>
<label id="msg" style="display: none"></label><br>
<input id="paw" name="paw" type="password" placeholder="密码"><br>
<br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.定义消息的实体类
public class Result {
public static Result NO_REGISTER = new Result(1,"恭喜,可以注册! ");
public static Result ALREADY_REGISTER = new Result(0, "已经被注册了,请换一个用户名!");
private int Code;
private String msg;
public Result() {
}
public Result(int code, String msg) {
Code = code;
this.msg = msg;
}
//get,set方法
)
3.编写Servlet
@WebServlet("/checkUsername")
public class LoginController extends javax.servlet.http.HttpServlet {
private List<String> list;
@Override
public void init(ServletConfig config) throws ServletException {
//模拟已经被注册的用户名
list = new ArrayList<String>();
list.add("zhangsan");
list.add("lisi");
list.add("wangwu");
list.add("zhaoliu");
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String username = request.getParameter("username");
Result result = null;
if(list.contains(username)){
result = Result.ALREADY_REGISTER;
}else{
result = Result.NO_REGISTER;
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().println(new ObjectMapper().writeValueAsString(result));
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request,response);
}
}
效果: