Java+Ajax實現使用者名稱重複檢驗

HuangQinJian發表於2019-02-14

今天,我來教大家怎麼實現Java+Ajax實現使用者名稱重複檢驗。

實體類程式碼:
package com.hqj.dao;
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 += ;//自由發揮複製程式碼

更多內容歡迎訪問我的個人主頁

Java+Ajax實現使用者名稱重複檢驗

相關文章