好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java+Ajax实现的用户名重复检验功能实例详解

本文实例讲述了java+ajax实现的用户名重复检验功能。分享给大家供大家参考,具体如下:

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

实体类代码:

?

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 + "]" ;

   }

}

数据库操作类代码:

?

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();

     }

   }

}

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

?

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实现

?

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://HdhCmsTestw3.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 的例子:

?

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 存储函数(或函数名),每当 readystate 属性改变时,就会调用该函数。
readystate 存有 xmlhttprequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

 

**在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

当 readystate 等于 4 且状态为 200 时,表示响应已就绪。**

?

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://HdhCmsTestw3.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对象是惟一的参数。

?

1

2

3

function(xmlhttprequest){

   this ;  //调用本次ajax请求时传递的options参数

}

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

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

?

1

2

3

function(xmlhttprequest, textstatus){

   this ;  //调用本次ajax请求时传递的options参数

}

success :要求为function类型的参数,请求成功后调用的回调函数,有两个参数。

(1)由服务器返回,并根据datatype参数进行处理后的数据。
(2)描述状态的字符串。

?

1

2

function(data, textstatus){

//data可能是xmldoc、jsonobj、html、text等等

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

ajax事件函数如下:

?

1

2

3

4

function(xmlhttprequest, textstatus, errorthrown){

  //通常情况下textstatus和errorthrown只有其中一个包含信息

  this ; //调用本次ajax请求时传递的options参数

}

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

示例代码:

?

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里面的所有内容

     var html = '' ;

     $.each(data, function(commentindex, comment){

     html += ; //自由发挥

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/sinat_35512245/article/details/71087162

查看更多关于Java+Ajax实现的用户名重复检验功能实例详解的详细内容...

  阅读:11次