本文實例講述了java+ajax實現(xiàn)的用戶名重復(fù)檢驗功能。分享給大家供大家參考,具體如下:
今天,我來教大家怎么實現(xiàn)java+ajax實現(xiàn)用戶名重復(fù)檢驗。
實體類代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
/** * */ 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 + "]" ; } } |
數(shù)據(jù)庫操作類代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/** * */ 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(); } } } |
上面的數(shù)據(jù)庫操作代碼相當(dāng)于一個工具類,大家可以直接使用,不過要記得改數(shù)據(jù)庫賬號,密碼以及數(shù)據(jù)庫表名:
1
2
|
conn = drivermanager .getconnection( "jdbc:mysql://localhost/system?user=root&password=729821" ); |
service類代碼:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * */ 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類代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * */ 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; } } |
后臺代碼:
1
2
3
4
5
6
7
8
|
<%@ 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實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
<%@ 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、要注意創(chuàng)建xmlhttp語句的正確性!
2、xmlhttp.send(“username=” + username);
是發(fā)送給后臺的(服務(wù)器)的數(shù)據(jù)!因為后臺需要前端傳送的數(shù)據(jù)進行判斷!
3、注意區(qū)分xmlhttp.responsetext
與responsexml的區(qū)別!
responsetext | 獲得字符串形式的響應(yīng)數(shù)據(jù)。 |
responsexml | 獲得 xml 形式的響應(yīng)數(shù)據(jù)。 |
如果來自服務(wù)器的響應(yīng)并非 xml,請使用 responsetext 屬性;如果來自服務(wù)器的響應(yīng)是 xml,而且需要作為 xml 對象進行解析,請使用 responsexml 屬性。
因為在我的代碼中后臺返回的是string類型,所以必須用responsetext。我剛開始時就是因為這個出錯了!
來一個 responsexml 的例子:
1
2
3
4
5
6
7
8
|
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 | 存儲函數(shù)(或函數(shù)名),每當(dāng) readystate 屬性改變時,就會調(diào)用該函數(shù)。 |
readystate |
存有 xmlhttprequest 的狀態(tài)。從 0 到 4 發(fā)生變化。 0: 請求未初始化 1: 服務(wù)器連接已建立 2: 請求已接收 3: 請求處理中 4: 請求已完成,且響應(yīng)已就緒 |
**在 onreadystatechange
事件中,我們規(guī)定當(dāng)服務(wù)器響應(yīng)已做好被處理的準備時所執(zhí)行的任務(wù)。
當(dāng) readystate 等于 4 且狀態(tài)為 200 時,表示響應(yīng)已就緒。**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
<%@ 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實現(xiàn)的時候,要注意$.ajax中的參數(shù):
url: 要求為string類型的參數(shù),(默認為當(dāng)前頁地址)發(fā)送請求的地址。
type: 要求為string類型的參數(shù),請求方式(post或get)默認為get。注意其他http請求方法,例如put和delete也可以使用,但僅部分瀏覽器支持。
timeout: 要求為number類型的參數(shù),設(shè)置請求超時時間(毫秒)。此設(shè)置將覆蓋$.ajaxsetup()方法的全局設(shè)置。
async:要求為boolean類型的參數(shù),默認設(shè)置為true,所有請求均為異步請求。 如果需要發(fā)送同步請求,請將此選項設(shè)置為false。注意,同步請求將鎖住瀏覽器,用戶其他操作必須等 待請求完成才可以執(zhí)行。
cache:要求為boolean類型的參數(shù),默認為true(當(dāng)datatype為script時,默認為false)。設(shè)置為false將不會從瀏覽器緩存中加載請求信息。
data: 要求為object或string類型的參數(shù),發(fā)送到服務(wù)器的數(shù)據(jù)。如果已經(jīng)不是字符串,將自動轉(zhuǎn)換為字符串格式。get請求中將附加在url后。防止這種自動轉(zhuǎn)換,可以查看processdata選項。對象必須為key/value格式,例如{foo1:”bar1”,foo2:”bar2”}轉(zhuǎn)換為&foo1=bar1&foo2=bar2。如果是數(shù)組,jquery將自動為不同值對應(yīng)同一個名稱。例如{foo:[“bar1”,”bar2”]}轉(zhuǎn)換為&foo=bar1&foo=bar2。
datatype: 要求為string類型的參數(shù),預(yù)期服務(wù)器返回的數(shù)據(jù)類型。如果不指定,jquery將自動根據(jù)http包mime信息返回responsexml或responsetext,并作為回調(diào)函數(shù)參數(shù)傳遞。
可用的類型如下:
- xml:返回xml文檔,可用jquery處理。
- html:返回純文本html信息;包含的script標簽會在插入dom時執(zhí)行。
- script:返回純文本javascript代碼。不會自動緩存結(jié)果。除非設(shè)置了cache參數(shù)。注意在遠程請求時(不在同一個域下),所有post請求都將轉(zhuǎn)為get請求。
- json:返回json數(shù)據(jù)。
- jsonp:jsonp格式。使用sonp形式調(diào)用函數(shù)時,例如myurl?callback=?,jquery將自動替換后一個 “?”為正確的函數(shù)名,以執(zhí)行回調(diào)函數(shù)。
- text:返回純文本字符串。
- beforesend:要求為function類型的參數(shù),發(fā)送請求前可以修改xmlhttprequest對象的函數(shù),例如添加自定義http頭。在beforesend中如果返回false可以取消本次ajax請求。xmlhttprequest對象是惟一的參數(shù)。
1
2
3
|
function(xmlhttprequest){ this ; //調(diào)用本次ajax請求時傳遞的options參數(shù) } |
- complete:要求為function類型的參數(shù),請求完成后調(diào)用的回調(diào)函數(shù)(請求成功或失敗時均調(diào)用)。
參數(shù):xmlhttprequest對象和一個描述成功請求類型的字符串。
1
2
3
|
function(xmlhttprequest, textstatus){ this ; //調(diào)用本次ajax請求時傳遞的options參數(shù) } |
- success:要求為function類型的參數(shù),請求成功后調(diào)用的回調(diào)函數(shù),有兩個參數(shù)。
(1)由服務(wù)器返回,并根據(jù)datatype參數(shù)進行處理后的數(shù)據(jù)。
(2)描述狀態(tài)的字符串。
1
2
|
function(data, textstatus){ //data可能是xmldoc、jsonobj、html、text等等 |
- error:要求為function類型的參數(shù),請求失敗時被調(diào)用的函數(shù)。該函數(shù)有3個參數(shù),即xmlhttprequest對象、錯誤信息、捕獲的錯誤對象(可選)。
ajax事件函數(shù)如下:
1
2
3
4
|
function(xmlhttprequest, textstatus, errorthrown){ //通常情況下textstatus和errorthrown只有其中一個包含信息 this ; //調(diào)用本次ajax請求時傳遞的options參數(shù) } |
- contenttype:要求為string類型的參數(shù),當(dāng)發(fā)送信息至服務(wù)器時,內(nèi)容編碼類型默認為”application/x-www-form-urlencoded”。該默認值適合大多數(shù)應(yīng)用場合。
示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
|
$(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里面的所有內(nèi)容 var html = '' ; $.each(data, function(commentindex, comment){ html += ; //自由發(fā)揮 |
希望本文所述對大家java程序設(shè)計有所幫助。
原文鏈接:https://blog.csdn.net/sinat_35512245/article/details/71087162