今天在b站上学习了一下如何用Ajax来验证用户是否可用(没有连接数据库)。因为之前在学习JavaScript和JavaWeb时,基础不是很好,所以有些语法格式都不记得了。接下来就是代码了。
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<!--
1.导入jQuery 库
2.获取name="username" 的节点:username
3.为username 添加change 响应函数
3.1 获取username 的value属性值,去除前后空格且不为空,准备发送Ajax请求
3.2 发送Ajax请求 检验username 是否可用
3.3 在服务器端直接返回一个HTML 的片段 :<font color="red">该用户名已经被使用</font>
3.4 在客户端浏览器把其直接添加到#message 的html中
-->
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(":input[name='username']").change(function(){
var val = $(this).val(); //获取值
val = $.trim(val); //去除空格
if(val != ""){
var url = "${pageContext.request.contextPath}/valiateUserName";//新建servlet时,映射路径要与此路径相同
var args ={"userName":val,"time":new Date()};
$.post(url,args,function(data){
$("#message").html(data); //将请求的内容放到 #message中
});
}
});
})
</script>
</head>
<body>
<form action="" method="post">
UserName:<input type="text" name="username"/>
<br><br>
<div id="message"></div>
<br><br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
然后新建一个Servlet
ValiateUserNameServlet.java
package com.jmi.ajax.app.servlet;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ValiateUserNameServlet
*/
@WebServlet("/valiateUserName")
public class ValiateUserNameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> userNames = Arrays.asList("aaa","bbb","ccc");
String userName = request.getParameter("userName");
String result = null;
if(userNames.contains(userName)){ //检查是否匹配
result = "<font color='red'>该用户名已经被使用</font>";
}else{
result = "<font color='green'>该用户名可以使用</font>";
}
response.setContentType("text/html ; charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result); //将result返回至data中
}
}
最后这是页面的效果
学的并不是很好,若大家有任何疑问或是不解的话,请在下方评论,谢谢。