首頁  >  文章  >  Java  >  實現AJAX+JAVA用戶登陸註冊驗證的程式碼

實現AJAX+JAVA用戶登陸註冊驗證的程式碼

coldplay.xixi
coldplay.xixi轉載
2020-08-24 17:33:363178瀏覽

實現AJAX+JAVA用戶登陸註冊驗證的程式碼

【相關學習推薦:java基礎教學

需求

透過ajax非同步刷新頁面驗證使用者輸入的帳號密碼是否在資料庫中存在。

技術堆疊

JSP Servlet Oracle

特定程式碼

JSP部分:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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>
<script>
  function createXMLHttpRequest() {
    try {
      xmlHttp = new XMLHttpRequest();//除了ie之外的其他浏览器使用ajax
    } catch (tryMS) {
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//ie浏览器适配
      } catch (otherMS) {
        try {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//ie浏览器适配
        } catch (failed) {
          xmlHttp = null;
        }
      }
    }
    return xmlHttp;
  }
  //提交请求
  var xmlHttp;
  function checkUserExists() {
    var u = document.getElementById("uname");
    var username = u.value;
    if (username == "") {
      alert("请输入用户名");
      u.focus();
      return false;
    }
    //访问字符串
    var url = "loginServlet";
    //创建核心xmlhttprequest组件
    xmlHttp = createXMLHttpRequest();
    //设置回调函数
    xmlHttp.onreadystatechange = proessRequest;
    //初始化核心组件
    xmlHttp.open("post", url, true);
    //设置请求头
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
    //发送请求
    xmlHttp.send("uname="+username);
  }
  //回调函数
  function proessRequest() {
    if (xmlHttp.status==200 && xmlHttp.readyState == 4) {
      var b = xmlHttp.responseText;//得到服务端的输出结果
      if (b=="true") {
        document.getElementById("alert").innerHTML = "<font color=&#39;red&#39;>用户名已经存在!</font>";
      }else {
        document.getElementById("alert").innerHTML = "<font color=&#39;blue&#39;>用户名可以使用!</font>";
      }
    }
  }
</script>
<body>
  请输入用户名:
  <input id="uname" name="uname" type="text" onblur="checkUserExists()" /><p id="alert" style="display:inline"></p>
</body>
</html>

這裡沒有用Dao層,直接用servlet和service層來驗證。

以下是service下JDBC查詢的程式碼:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.stx.service.User;
import com.stx.service.ConnectionManager;

public class ajaxService {
  public boolean searchUser (String uname) {
  //jdbc查询用户名是否存在
    boolean isFalse = false;
    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;
    connection = ConnectionManager.getConnection();
    try {
      stmt = connection.createStatement();
      String sql = "select * from user_b where uname=&#39;"+uname+"&#39;";//sql语句
      rs = stmt.executeQuery(sql);
      isFalse=rs.next();

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      ConnectionManager.closeResultSet(rs);
      ConnectionManager.closeStatement(stmt);
      ConnectionManager.closeConnection(connection);
    }
    return isFalse;
  }
}

JDBC連線程式碼:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ConnectionManager {
  private final static String DRIVER_CLASS = "oracle.jdbc.OracleDriver";
  private final static String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
  private final static String DBNAME = "ibook";
  private final static String PASSWORD = "qwer";

  public static Connection getConnection() {
    Connection connection = null;
    try {
      Class.forName(DRIVER_CLASS);
      connection = DriverManager.getConnection(URL, DBNAME, PASSWORD);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return connection;
  }

  public static void closeResultSet(ResultSet rs) {
    try {
      if (rs != null)
        rs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void closeConnection(Connection connection) {
    try {
      if (connection != null && !connection.isClosed())
        connection.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void closeStatement(Statement stmt) {
    try {
      if (stmt != null)
        stmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

關於user類別:

 public class User {
    private String uname;
    public User() {
      super();
    }
    public User(String uname) {
      super();
      this.uname = uname;
  
    }
  
    public String getUname() {
      return uname;
    }
    public void setUname(String uname) {
      this.uname = uname;
    }

關於控制層servlet:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stx.service.ajaxService;

/**
 * Servlet implementation class loginServlet
 */
public class loginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private ajaxService ajaxService = new ajaxService();

  /**
   * @see HttpServlet#HttpServlet()
   */
  public loginServlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String uname = request.getParameter("uname");//获取到输入的用户名
    boolean isUname = ajaxService.searchUser(uname);//调用service中的查询方法
    response.setCharacterEncoding("UTF-8");//设置字符编码
    PrintWriter out = response.getWriter();
    out.print(isUname);
    out.flush();
    out.close();//关闭资源
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}

相關文章推薦:ajax影片教學

以上是實現AJAX+JAVA用戶登陸註冊驗證的程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除