Java+Ajax实现用户名重复检验

简介: 今天,我来教大家怎么实现Java+Ajax实现用户名重复检验。实体类代码:/** * */package com.

今天,我来教大家怎么实现Java+Ajax实现用户名重复检验。

实体类代码:

/**
 *
 */
package com.hqj.dao;

/**
 * @author HuangQinJian 下午9:12:19 2017年4月23日
 */
public class User {
    private int id;
    private String name;
    private String password;

    /**
     *
     */
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @param id
     * @param name
     * @param password
     */
    public User(int id, String name, String password) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", password=" + password + "]";
    }
}

数据库操作类代码:

/**
 *
 */
package com.hqj.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author HuangQinJian 上午9:21:23 2017年4月24日
 */
public class DBConnection {
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager
                    .getConnection("jdbc:mysql://localhost/system?user=root&password=729821");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static PreparedStatement prepare(Connection conn, String sql) {
        PreparedStatement pstmt = null;
        try {
            if (conn != null) {
                pstmt = conn.prepareStatement(sql);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pstmt;
    }

    public static PreparedStatement prepare(Connection conn, String sql,
            int autoGenereatedKeys) {
        PreparedStatement pstmt = null;
        try {
            if (conn != null) {
                pstmt = conn.prepareStatement(sql, autoGenereatedKeys);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pstmt;
    }

    public static Statement getStatement(Connection conn) {
        Statement stmt = null;
        try {
            if (conn != null) {
                stmt = conn.createStatement();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return stmt;
    }

    public static ResultSet getResultSet(Statement stmt, String sql) {
        ResultSet rs = null;
        try {
            if (stmt != null) {
                rs = stmt.executeQuery(sql);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static void executeUpdate(Statement stmt, String sql) {
        try {
            if (stmt != null) {
                stmt.executeUpdate(sql);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

上面的数据库操作代码相当于一个工具类,大家可以直接使用,不过要记得改数据库账号,密码以及数据库表名:

conn = DriverManager
        .getConnection("jdbc:mysql://localhost/system?user=root&password=729821");

service类代码:

/**
 *
 */
package com.hqj.service;

import java.util.List;

import com.hqj.dao.User;

/**
 * @author HuangQinJian 上午9:26:26 2017年4月24日
 */
public interface UserService {
    public String checkUserName(String username);
}

serviceImpl类代码:

/**
 *
 */
package com.hqj.serviceImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.hqj.dao.User;
import com.hqj.db.DBConnection;
import com.hqj.service.UserService;

/**
 * @author HuangQinJian 上午9:29:14 2017年4月24日
 */
public class UserServiceImpl implements UserService {

    private Connection conn = null;
    private Statement stmt = null;
    private PreparedStatement pstmt = null;
    DBConnection dbConnection = new DBConnection();

    @Override
    public String checkUserName(String username) {
        conn = DBConnection.getConn();
        stmt = DBConnection.getStatement(conn);
        String sql = "select * from user where name=" + "'" + username + "'";
        System.out.println("用户查询时的SQL:" + sql);
        String str = null;
        try {
            pstmt = conn.prepareStatement(sql);
            if (pstmt.executeQuery().next() == true) {
                str = "用户名已存在!";
            } else {
                str = "用户名可用!";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return str;
    }
}

后台代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.hqj.serviceImpl.UserServiceImpl"%>
<%
    String username = request.getParameter("username");
    UserServiceImpl u = new UserServiceImpl();
    out.println(u.checkUserName(username));
%>

前端代码:

利用原生Ajax实现

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.hqj.dao.User"%>
<%@ page import="com.hqj.serviceImpl.UserServiceImpl"%>
<!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>
</head>
<body>
    <form action="regeist.jsp" method="post">
        用户名: <input type="text" value="" name="name" id="username"
            onblur='checkUserName()'>
        <br> 密码: <input type="text" value="" name="password"><br>
        <input type="submit" value="提交">
    </form>
    <jsp:useBean id="user" scope="session" class="com.hqj.dao.User"></jsp:useBean>
    <jsp:setProperty property="name" name="user" />
    <jsp:setProperty property="password" name="user" />
    <%
        if (request.getMethod() == "POST") {
            User u = new User();
            u.setName(user.getName());
            out.println(user.getName());
            u.setPassword(user.getPassword());
            UserServiceImpl userServiceImpl = new UserServiceImpl();
            if (!userServiceImpl.checkUserName(user.getName()).equals(
                    "用户名已存在!")) {
                userServiceImpl.add(u);
                out.println("用户注册成功!");
            }
        }
    %>
    <h3><%=user.getName()%></h3>
    <h3><%=user.getPassword()%></h3>
</body>
<script type="text/javascript">
    var xmlhttp;
    var flag;
    function createXMLHttp() {
        if (window.ActiveXObject) {
            //ie  
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            //firefox  
            xmlhttp = new XMLHttpRequest();
        }

    }

    function checkUserName() {
        createXMLHttp();
        var username = document.getElementById("username").value;
        //  alert(username);
        if (username == "") {
            document.getElementById("username").innerHTML = "用户名不能为空";
        }

        xmlhttp.open("POST", "checkUserName.jsp", true);
        xmlhttp.setRequestHeader("Content-type",
                "application/x-www-form-urlencoded");
        xmlhttp.send("username=" + username);
        xmlhttp.onreadystatechange = function() {
            //      alert(xmlhttp.readyState);
            //      alert(xmlhttp.status);
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                console.log(xmlhttp.responseText);
                document.getElementById("text").innerHTML = xmlhttp.responseText;
            }
        }
    }
</script>
</html>

在这里有几个点需要注意:

1、要注意创建xmlhttp语句的正确性!

2、xmlhttp.send(“username=” + username);是发送给后台的(服务器)的数据!因为后台需要前端传送的数据进行判断!

3、注意区分xmlhttp.responseText与responseXML的区别!

responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。

如果来自服务器的响应并非 XML,请使用 responseText 属性;如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性。

因为在我的代码中后台返回的是String类型,所以必须用responseText。我刚开始时就是因为这个出错了!

来一个 responseXML 的例子:

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
    txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;
属性 描述
onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

**在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪。**

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.hqj.dao.User"%>
<%@ page import="com.hqj.serviceImpl.UserServiceImpl"%>
<!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>
</head>
<body>
    <form action="regeist.jsp" method="post">
        用户名: <input type="text" value="" name="name" id="username">
        <div id="text"></div>
        <br> 密码: <input type="text" value="" name="password"><br>
        <input type="submit" value="提交">
    </form>
    <jsp:useBean id="user" scope="session" class="com.hqj.dao.User"></jsp:useBean>
    <jsp:setProperty property="name" name="user" />
    <jsp:setProperty property="password" name="user" />
    <%
        if (request.getMethod() == "POST") {
            User u = new User();
            u.setName(user.getName());
            out.println(user.getName());
            u.setPassword(user.getPassword());
            UserServiceImpl userServiceImpl = new UserServiceImpl();
            if (!userServiceImpl.checkUserName(user.getName()).equals(
                    "用户名已存在!")) {
                userServiceImpl.add(u);
                out.println("用户注册成功!");
            }
        }
    %>
    <h3><%=user.getName()%></h3>
    <h3><%=user.getPassword()%></h3>
</body>
<script type="text/javascript" src="js/jquery-2.2.3.js"></script>
<script type="text/javascript">
    /* $(document).ready(function() {
    alert("hello world!");
    }); */
    var username;
    $("#username").blur(function() {
        username = $('#username').val();
        //console.log(username);
        $.ajax({
            url : "checkUserName.jsp",
            type : "POST",
            dataType : "text",
            data : {
                "username" : username
            },
            success : function(data) {
                //$("#text").innerHTML = data;
                //console.log(data)
                $("#text").text(data);
            }
        })
    })
</script>
</html>

使用JQuery实现的时候,要注意$.ajax中的参数:

url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。

type: 要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。

timeout: 要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。

async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。 如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等 待请求完成才可以执行。

cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false)。设置为false将不会从浏览器缓存中加载请求信息。

data: 要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格式,例如{foo1:”bar1”,foo2:”bar2”}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:[“bar1”,”bar2”]}转换为&foo=bar1&foo=bar2。

dataType: 要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。

可用的类型如下:

  • xml:返回XML文档,可用JQuery处理。
  • html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
  • script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
  • json:返回JSON数据。
  • jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个 “?”为正确的函数名,以执行回调函数。
  • text:返回纯文本字符串。

beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。

            function(XMLHttpRequest){
               this;   //调用本次ajax请求时传递的options参数
            }

complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。

参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。

          function(XMLHttpRequest, textStatus){
             this;    //调用本次ajax请求时传递的options参数
          }

success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
(1)由服务器返回,并根据dataType参数进行处理后的数据。
(2)描述状态的字符串。

function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等

error:要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。

ajax事件函数如下:

function(XMLHttpRequest, textStatus, errorThrown){
  //通常情况下textStatus和errorThrown只有其中一个包含信息
  this; //调用本次ajax请求时传递的options参数
 }

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为”application/x-www-form-urlencoded”。该默认值适合大多数应用场合。

示例代码:

$(function(){
 $('#send').click(function(){
   $.ajax({
    type: "GET",
    url: "test.json",
    data: {username:$("#username").val(), content:$("#content").val()},
    dataType: "json",
    success: function(data){
       $('#resText').empty(); //清空resText里面的所有内容
       var html = '';
       $.each(data, function(commentIndex, comment){
        html += ;//自由发挥

更多内容欢迎访问我的个人主页

相关文章
|
1月前
|
JSON 前端开发 JavaScript
|
9月前
|
JSON 前端开发 Java
Java Web应用开发案例|使用AJAX实现省市区三级联动效果
使用AJAX实现省市区三级联动效果,即选择省后,该省下的所有市数据动态填充到下拉框中,区县数据也会根据市的变化而动态填充该市下的区县数据。
93 0
Java Web应用开发案例|使用AJAX实现省市区三级联动效果
|
4月前
|
消息中间件 缓存 运维
【Java】医院云HIS信息管理系统源码:实现检验、检查、心理CT、B超等医技报告查看
【Java】医院云HIS信息管理系统源码:实现检验、检查、心理CT、B超等医技报告查看
47 0
|
7月前
|
XML JSON 前端开发
【Java】数据交换 Json 和 异步请求 Ajax
JSON: JavaScript Object Notation(JavaScript 对象标记法)。 JSON 是一种存储和交换数据的语法。 JSON 是通过 JavaScript 对象标记法书写的文本。 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式 (String) JSON易于阅读和编写的文本形式表示数据 JSON数据使用键值对的方式进行组织,并且可以包含数组、对象和简单的数据类型(例如字符串、数字、布尔值和null)
|
Java
Java 实现汉字按照首字母分组排序
Java 实现汉字按照首字母分组排序
561 0
|
10月前
|
JSON 前端开发 Java
ajax+json校验用户名是否存在
ajax+json校验用户名是否存在
|
10月前
|
算法 Java
Java给定一个字符串 如何检验一个日期是否为有效日期
Java给定一个字符串 如何检验一个日期是否为有效日期
74 0
|
11月前
|
前端开发 Java
java实现动态验证码源代码——接受ajax的jsp
java实现动态验证码源代码——接受ajax的jsp
43 0
|
11月前
|
JSON 前端开发 Java
【Java框架型项目从入门到装逼】第六节 - 用ajax请求后台数据
【Java框架型项目从入门到装逼】第六节 - 用ajax请求后台数据
|
存储 Oracle NoSQL
基于 Java SpringMVC、Ajax、JQueryMySQL、Redis开发的在线学习平台
基于 Java SpringMVC、Ajax、JQueryMySQL、Redis开发的在线学习平台
129 0
基于 Java SpringMVC、Ajax、JQueryMySQL、Redis开发的在线学习平台