Java + Ajax implementation of user name duplicate verification

qinjianhuang 2020-11-13 05:26:30
java ajax implementation user duplicate


today , Let me show you how to achieve Java+Ajax Implement user name verification repeatedly .

Entity class code :

/**
*
*/
package com.hqj.dao;
/**
* @author HuangQinJian Afternoon 9:12:19 2017 year 4 month 23 Japan
*/
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 + "]";
}
}

Database operation class code :

/**
*
*/
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 In the morning 9:21:23 2017 year 4 month 24 Japan
*/
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();
}
}
}

The above database operation code is equivalent to a tool class , You can use it directly , But remember to change the database account , Password and database table name :

conn = DriverManager
.getConnection("jdbc:mysql://localhost/system?user=root&password=729821");

service Class code :

/**
*
*/
package com.hqj.service;
import java.util.List;
import com.hqj.dao.User;
/**
* @author HuangQinJian In the morning 9:26:26 2017 year 4 month 24 Japan
*/
public interface UserService {

public String checkUserName(String username);
}

serviceImpl Class code :

/**
*
*/
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 In the morning 9:29:14 2017 year 4 month 24 Japan
*/
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(" When the user inquires SQL:" + sql);
String str = null;
try {
pstmt = conn.prepareStatement(sql);
if (pstmt.executeQuery().next() == true) {
str = " User name already exists !";
} else {
str = " User name available !";
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
}

Background code :

<%@ 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));
%>

The front-end code :

Use native Ajax Realization

<%@ 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">
user name : <input type="text" value="" name="name" id="username"
onblur='checkUserName()'>
<br> password : <input type="text" value="" name="password"><br>
<input type="submit" value=" Submit ">
</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(
" User name already exists !")) {
userServiceImpl.add(u);
out.println(" User registration successful !");
}
}
%>
<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 = " The username cannot be empty ";
}
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>

Here are a few points to pay attention to :

1、 Pay attention to creating xmlhttp Statement correctness !

2、xmlhttp.send(“username=” + username); It's sent to the backstage ( The server ) The data of ! Because the background needs to judge the data transmitted by the front end !

3、 Pay attention to distinguish between xmlhttp.responseText And responseXML The difference between !

responseText Get response data as a string .
responseXML get XML Response data in form .

If the response from the server is not XML, Please use responseText attribute ; If the response from the server is XML, And it needs to be XML Object parsing , Please use responseXML attribute .

Because in my code, what is returned in the background is String type , So we have to use responseText. It was because of this that I made a mistake at the beginning !

To a responseXML Example :

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;
attribute describe
onreadystatechange Storage function ( Or function name ), whenever readyState When attributes change , The function will be called .
readyState come into being XMLHttpRequest The state of . from 0 To 4 change .
0: Request not initialized
1: Server connection established
2: Request received
3: Request processing
4: Request completed , And the response is ready

** stay onreadystatechange Incident , We define the tasks to be performed when the server response is ready to be processed .
When readyState be equal to 4 And the state is 200 when , Indicates response is ready .**

<%@ 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">
user name : <input type="text" value="" name="name" id="username">
<div id="text"></div>
<br> password : <input type="text" value="" name="password"><br>
<input type="submit" value=" Submit ">
</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(
" User name already exists !")) {
userServiceImpl.add(u);
out.println(" User registration successful !");
}
}
%>
<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>

Use JQuery When it's done , it is to be noted that $.ajax Parameters in :

url: Requirements for String Parameters of type ,( The default is the current page address ) Address to send request .

type: Requirements for String Parameters of type , Request mode (post or get) The default is get. Pay attention to other http Request method , for example put and delete You can also use , But only some browsers support .

timeout: Requirements for Number Parameters of type , Set request timeout ( millisecond ). This setting will override $.ajaxSetup() Method's global settings .

async: Requirements for Boolean Parameters of type , The default setting is true, All requests are asynchronous . If you need to send a synchronization request , Please set this option to false. Be careful , The synchronization request will lock the browser , Other user operations must wait Wait until the request is completed to execute .

cache: Requirements for Boolean Parameters of type , The default is true( When dataType by script when , The default is false). Set to false Request information will not be loaded from the browser cache .

data: Requirements for Object or String Parameters of type , Data sent to server . If it's not already a string , Automatically convert to string format .get The request will be attached to url after . Prevent this automatic conversion , You can see processData Options . The object must be key/value Format , for example {foo1:”bar1”,foo2:”bar2”} Convert to &foo1=bar1&foo2=bar2. If it's an array ,JQuery Will automatically correspond to the same name for different values . for example {foo:[“bar1”,”bar2”]} Convert to &foo=bar1&foo=bar2.

dataType: Requirements for String Parameters of type , Expected data type returned by the server . If you don't specify ,JQuery Will automatically follow http package mime Information return responseXML or responseText, And passed as a callback function parameter .

The types available are :

  • xml: return XML file , You can use JQuery Handle .
  • html: Return to plain text HTML Information ; Contains script The label will insert DOM When the .
  • script: Return to plain text JavaScript Code . Results will not be automatically cached . Unless set cache Parameters . Note that when requesting remotely ( Not in the same domain ), all post All requests will be converted to get request .
  • json: return JSON data .
  • jsonp:JSONP Format . Use SONP When a function is called in form , for example myurl?callback=?,JQuery Will automatically replace the next “?” Is the correct function name , To execute a callback function .
  • text: Returns a plain text string .

beforeSend: Requirements for Function Parameters of type , It can be modified before sending the request XMLHttpRequest Object function , For example, add custom HTTP head . stay beforeSend If you return to false You can cancel this ajax request .XMLHttpRequest Object is the only parameter .

 function(XMLHttpRequest){

this; // Call this time ajax Delivered on request options Parameters 
}

complete: Requirements for Function Parameters of type , Callback function called after request completion ( Called when the request succeeds or fails ).

Parameters :XMLHttpRequest Object and a string describing the type of successful request .

 function(XMLHttpRequest, textStatus){

this; // Call this time ajax Delivered on request options Parameters 
}

success: Requirements for Function Parameters of type , Callback function called after successful request , There are two parameters .
(1) Returned by server , And according to dataType Data after parameter processing .
(2) String describing the State .

function(data, textStatus){

//data May be xmlDoc、jsonObj、html、text wait 

error: Requirements for Function Parameters of type , Function called when the request fails . This function is 3 Parameters , namely XMLHttpRequest object 、 error message 、 Wrong object captured ( Optional ).

ajax The event functions are as follows :

function(XMLHttpRequest, textStatus, errorThrown){

// Usually textStatus and errorThrown Only one of them contains information 
this; // Call this time ajax Delivered on request options Parameters 
}

contentType: Requirements for String Parameters of type , When sending a message to the server , The content encoding type defaults to ”application/x-www-form-urlencoded”. This default value is suitable for most applications .

Sample code :

$(function(){

$('#send').click(function(){

$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
success: function(data){

$('#resText').empty(); // Empty resText Everything in it 
var html = '';
$.each(data, function(commentIndex, comment){

html += ;// Free play 

For more information, please visit my homepage

版权声明
本文为[qinjianhuang]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple