本文实例为大家分享了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);
}
}
效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:JavaWeb实现注册用户名检测
基础教程推荐
猜你喜欢
- springboot自定义starter方法及注解实例 2023-03-31
- ConditionalOnProperty配置swagger不生效问题及解决 2023-01-02
- Java数据结构之对象比较详解 2023-03-07
- Java文件管理操作的知识点整理 2023-05-19
- JDK数组阻塞队列源码深入分析总结 2023-04-18
- Java并发编程进阶之线程控制篇 2023-03-07
- java实现多人聊天系统 2023-05-19
- java基础知识之FileInputStream流的使用 2023-08-11
- Java实现查找文件和替换文件内容 2023-04-06
- Java实现线程插队的示例代码 2022-09-03