AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
AJAX = 异步 JavaScript 和 XML。AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
使用jQuery进行异步请求验证,在开发中最常使用,实际开发过程中必须会使用的技术,jQuery可以到官网进行下载。
下面介绍如何使jQuery进行开发,需要注意的是要引入一个jQuery的js,如下:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
步骤说明
1、代码请参考——第十六篇JDBC操作数据库之监听器。
2、在第十六篇基础上继续实现功能——第十七篇JDBC操作数据库之Ajax异步验证
一、registerAjax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>注册页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//用户名文本框绑定失去焦点事件
$("#username").blur(function () {
// alert("blur: " + $(this).val());
$.ajax({
url:"UserCheckAjax2",//设置服务器地址,即为servlet配置的url-pattern,注意不用"/"符号
type:"post",//提交方式
data:{username:$(this).val()},//提交到服务器的数据,多个值以逗号分割
success:function (data) { //回调函数,data是返回的数据
// alert("data: " + data);
$("#errorUsername").html(data);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post">
<table>
<caption>注册页面</caption>
<tr>
<td align="right">账号:</td>
<td>
<input type="text" name="username" id="username">
<div id="errorUsername" name="errorUsername" style="color: red;display: inline"></div>
</td>
</tr>
<tr>
<td align="right">密码:</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td align="right">确定密码:</td>
<td><input type="text" name="repassword"></td>
</tr>
<tr>
<td align="right">性别:</td>
<td>
<input type="radio" name="sex" value="男" checked="checked">男
<input type="radio" name="sex" value="女">女
</td>
</tr>
<tr>
<td align="right">头像:</td>
<td>
<select name="photo" id="photo" οnchange="change();">
<option value="images/boy.png" selected="selected">boy</option>
<option value="images/girl.png">girl</option>
</select>
<img id="photoImg" src="images/boy.png">
</td>
</tr>
<tr>
<td align="right">联系电话:</td>
<td><input type="text" name="tel"></td>
</tr>
<tr>
<td align="right">电子邮箱:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
二、UserCheckAjax2 .java
package com.control;
import com.model.UserDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ray on 2018/3/18 0018.
**/
public class UserCheckAjax2 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 {
//获取页面传来的数据
String username = request.getParameter("username");
//调用模型
UserDao userDao = new UserDao();
//判断用户名在数据库中是否存在
boolean makr = userDao.userIsExist(username);
System.out.println("makr: " + makr);
//响应页面
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if(!makr){
out.println("<font color='red'>该用户名已经存在,请重新输入!!</font>");
}else{
out.println("<font color='green'>恭喜您,该用户名可以使用!!</font>");
}
//刷新流
out.flush();
//关闭流
out.close();
}
}
三、UserDao.java
package com.model;
import com.dbutil.Dbconn;
import com.entity.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Created by Ray on 2018/3/14 0014.
**/
public class UserDao {
User user = null;
Dbconn dbconn = new Dbconn();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
/**
* @Author: Ray
* @Date: 2018/3/14 0014
* @Description: 用户登录
* @Return: User对象
*/
public User login(String username,String password){
//数据库连接
connection = dbconn.getConnection();
//查询是否用户和密码
String sql = "select * from user where username = ? and password = ?";
try {
//获取PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
//对占位符进行动态赋值
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
//执行查询并获取结果集
resultSet = preparedStatement.executeQuery();
//判断结果集是否有效
if(resultSet.next()){
//实例化user对象
user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setSex(resultSet.getString("sex"));
user.setTel(resultSet.getString("tel"));
user.setPhoto(resultSet.getString("photo"));
user.setEmail(resultSet.getString("email"));
}
//释放资源
resultSet.close();
preparedStatement.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
return user;
}
/**
* @Author: Ray
* @Date: 2018/3/14 0014
* @Description: 判断用户名在数据库中是否存在
* @Return: boolean
*/
public boolean userIsExist(String username){
//获取数据库连接
connection = dbconn.getConnection();
//根据用户名查询的sql语句
String sql = "select * from user where username = ?";
try{
//获取PreparedStatement对象
preparedStatement= connection.prepareStatement(sql);
//对占位符进行动态赋值
preparedStatement.setString(1,username);
//执行查询并获取结果集
resultSet = preparedStatement.executeQuery();
//判断结果集是否有效
if(!resultSet.next()){
//如果无效则证明此用户名可用
return true;
}
//释放资源
resultSet.close();
preparedStatement.close();
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* @Author: Ray
* @Date: 2018/3/14 0014
* @Description: 新增用户
* @Return:
*/
public void addUser(User user){
//获取数据库连接
connection = dbconn.getConnection();
//新增用户信息的sql语句
String sql = "insert into user(username,password,sex,tel,photo,email) values (?,?,?,?,?,?)";
try{
//获取PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
//对占位符进行动态赋值
preparedStatement.setString(1,user.getUsername());
preparedStatement.setString(2,user.getPassword());
preparedStatement.setString(3,user.getSex());
preparedStatement.setString(4,user.getTel());
preparedStatement.setString(5,user.getPhoto());
preparedStatement.setString(6,user.getEmail());
//执行新增操作
preparedStatement.executeUpdate();
//释放资源
preparedStatement.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
四、web.xml
<!--Ajax-->
<servlet>
<servlet-name>UserCheckAjax2</servlet-name>
<servlet-class>com.control.UserCheckAjax2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserCheckAjax2</servlet-name>
<url-pattern>/UserCheckAjax2</url-pattern>
</servlet-mapping>
五、页面效果
数据库已存在用户
ok!