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

今天,我来教大家怎么实现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>
<  http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
< >Insert   here</ >
</head>
<body>
  <form action=\"regeist.jsp\" method=\"post\">
    用户名: <input type=\"text\" value=\"\" name=\"name\" id=\"username\"
       =\'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>
<  type=\"text/ \">
  var  http;
  var flag;
  function create Http() {
    if (window.ActiveX ) {
      //ie
       http = new ActiveX (\"Microsoft. HTTP\");
    } else {
      //firefox
       http = new  HttpRequest();
    }
  }
  function checkUserName() {
    create Http();
    var username = document.getElementById(\"username\").value;
    // alert(username);
    if (username == \"\") {
      document.getElementById(\"username\").innerHTML = \"用户名不能为空\";
    }
     http.open(\"POST\", \"checkUserName.jsp\", true);
     http.setRequestHeader(\"Content-type\",
        \"application/x-www-form-urlencoded\");
     http.send(\"username=\" + username);
     http.  = function() {
      //   alert( http.readyState);
      //   alert( http.status);
      if ( http.readyState == 4 &&  http.status == 200) {
        console.log( http.responseText);
        document.getElementById(\"text\").innerHTML =  http.responseText;
      }
    }
  }
</ >
</html>

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

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

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

3、注意区分 http.responseText与response 的区别!

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

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

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

来一个 response 的例子:

 Doc= http.response ;
txt=\"\";
x= Doc.getElementsByTagName(\"ARTIST\");
for (i=0;i<x.length;i++)
{
  txt=txt + x[i].childNodes[0].nodeValue + \"<br>\";
}
document.getElementById(\"myDiv\").innerHTML=txt;

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

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

当 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>
<  http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
< >Insert   here</ >
</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>
<  type=\"text/ \" src=\"js/jquery-2.2.3.js\"></ >
<  type=\"text/ \">
  /* $(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);
      }
    })
  })
</ >
</html>

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

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

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

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

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

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

data: 要求为 或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信息返回response 或responseText,并作为回调函数参数传递。

可用的类型如下:

  • :返回 文档,可用JQuery处理。
  • html:返回纯文本HTML信息;包含的 标签会在插入DOM时执行。
  • :返回纯文本 代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
  • json:返回JSON数据。
  • jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个 “?”为正确的函数名,以执行回调函数。
  • text:返回纯文本字符串。
  • beforeSend:要求为Function类型的参数,发送请求前可以修改 HttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。 HttpRequest对象是惟一的参数。
function( HttpRequest){
  this;  //调用本次ajax请求时传递的options参数
}

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

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

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

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

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

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

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

ajax事件函数如下:

function( HttpRequest, 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算法相关内容感兴趣的读者可查看本站专题:《Java正则表达式技巧大全》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

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

收藏 打印