麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發(fā) > Java > 正文

Java+Ajax實現(xiàn)的用戶名重復(fù)檢驗功能實例詳解

2024-07-14 08:43:08
字體:
供稿:網(wǎng)友

本文實例講述了Java+Ajax實現(xiàn)的用戶名重復(fù)檢驗功能。分享給大家供大家參考,具體如下:

今天,我來教大家怎么實現(xiàn)Java+Ajax實現(xiàn)用戶名重復(fù)檢驗。

實體類代碼:

/** * */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ù)庫操作類代碼:

/** * */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ù)庫表名:

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實現(xiàn)

<%@ 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ù)進(jìn)行判斷!

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 對象進(jìn)行解析,請使用 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 存儲函數(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ǔn)備時所執(zhí)行的任務(wù)。

當(dāng) readyState 等于 4 且狀態(tài)為 200 時,表示響應(yīng)已就緒。**

<%@ 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ù),(默認(rèn)為當(dāng)前頁地址)發(fā)送請求的地址。

type: 要求為String類型的參數(shù),請求方式(post或get)默認(rèn)為get。注意其他http請求方法,例如put和delete也可以使用,但僅部分瀏覽器支持。

timeout: 要求為Number類型的參數(shù),設(shè)置請求超時時間(毫秒)。此設(shè)置將覆蓋$.ajaxSetup()方法的全局設(shè)置。

async:要求為Boolean類型的參數(shù),默認(rèn)設(shè)置為true,所有請求均為異步請求。 如果需要發(fā)送同步請求,請將此選項設(shè)置為false。注意,同步請求將鎖住瀏覽器,用戶其他操作必須等 待請求完成才可以執(zhí)行。

cache:要求為Boolean類型的參數(shù),默認(rèn)為true(當(dāng)dataType為script時,默認(rèn)為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標(biāo)簽會在插入DOM時執(zhí)行。
  • script:返回純文本JavaScript代碼。不會自動緩存結(jié)果。除非設(shè)置了cache參數(shù)。注意在遠(yuǎn)程請求時(不在同一個域下),所有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ù)。
function(XMLHttpRequest){  this;  //調(diào)用本次ajax請求時傳遞的options參數(shù)}
  • complete:要求為Function類型的參數(shù),請求完成后調(diào)用的回調(diào)函數(shù)(請求成功或失敗時均調(diào)用)。

參數(shù):XMLHttpRequest對象和一個描述成功請求類型的字符串。

function(XMLHttpRequest, textStatus){  this;  //調(diào)用本次ajax請求時傳遞的options參數(shù)}
  • success:要求為Function類型的參數(shù),請求成功后調(diào)用的回調(diào)函數(shù),有兩個參數(shù)。

(1)由服務(wù)器返回,并根據(jù)dataType參數(shù)進(jìn)行處理后的數(shù)據(jù)。
(2)描述狀態(tài)的字符串。

function(data, textStatus){//data可能是xmlDoc、jsonObj、html、text等等
  • error:要求為Function類型的參數(shù),請求失敗時被調(diào)用的函數(shù)。該函數(shù)有3個參數(shù),即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。

ajax事件函數(shù)如下:

function(XMLHttpRequest, textStatus, errorThrown){ //通常情況下textStatus和errorThrown只有其中一個包含信息 this; //調(diào)用本次ajax請求時傳遞的options參數(shù)}
  • contentType:要求為String類型的參數(shù),當(dāng)發(fā)送信息至服務(wù)器時,內(nèi)容編碼類型默認(rèn)為”application/x-www-form-urlencoded”。該默認(rèn)值適合大多數(shù)應(yīng)用場合。

示例代碼:

$(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è)計有所幫助。


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 国产成人午夜高潮毛片 | 久久恋 | 久久人人做 | 久久免费视频一区二区三区 | 羞羞视频免费观看入口 | 国产美女一区二区在线观看 | 制服丝袜日日夜夜 | 欧美日韩一区,二区,三区,久久精品 | 精品国产一区二区三区四 | 亚洲精久| 国产一级二级视频 | 欧美成人性色 | 欧美激情猛片xxxⅹ大3 | 日韩视频1 | 91久久国产露脸精品免费 | 国产精品视频中文字幕 | 国产一区视频免费观看 | 亚洲精品一区二区三区免 | 国产精品久久久久久久久粉嫩 | 最新欧美精品一区二区三区 | 最新黄色电影网站 | 成人羞羞视频在线观看免费 | 久久思思爱 | 99精品国产成人一区二区 | 免费看真人a一级毛片 | av电影院在线观看 | 精品国产乱码久久久久久丨区2区 | 亚洲第一男人天堂 | 欧美日韩专区国产精品 | 欧美成人小视频 | 羞羞视频免费网站男男 | 国产免费资源 | 免费视频a | 亚洲一二区精品 | 91一区二区三区久久久久国产乱 | 黄色免费播放网站 | 91短视频版高清在线观看www | 在线看91| 国产精品二区高清在线 | 国产亚洲精品久久久久久久软件 | 国产91丝袜在线播放 |