Ajax&Ajax asynchronous verification of user name in Java

Ajax

Asynchronous JavaScript And XML (Asynchronous JavaScript And XML) is a web development technology that creates interactive web applications. Ajax is not a new technology, but a combination of original technology. It is composed of the following technologies:
  • Using CSS and XHTML to represent
  • Interaction and dynamic display using DOM model
  • Asynchronous communication with server using XMLHttpRequest
  • Using JavaScript to bind and call

1. role

It can update some data without refreshing the whole page.

2. Internal principle [simple understanding]

For example: determine whether the user name has been registered
Traditional way:

  1. Enter the user name;
  2. Click a button to verify;
  3. Give the data to the server;
  4. The server completes the verification in the background and feeds back the information;
  5. Prompt the user on the browser.

Ajax mode:

  1. Get the text content of input box document.getElementById("username"). value through JS
  2. Execute the request through XMLHttpRequest;
  3. After the request, you receive the result, and then use js to complete the prompt. * *

3.1 data request Get

1. Create objects;
function  ajaxFunction(){
			   var xmlHttp;
			   try{ // Firefox, Opera 8.0+, Safari
			        xmlHttp = new XMLHttpRequest();
			    }
			    catch (e){
				   try{// Internet Explorer
				         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
				      }
				    catch (e){
				      try{
				         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				      }
				      catch (e){}
				      }
			    }
		
				return xmlHttp;
			 }
2. Send the request;
	//Execute get request
	function get() {
		
		//1. Create xmlhttprequest object
		var request = ajaxFunction();
		
		//2. Send the request.
		/*	
			Parameter 1: request type get or post
			Parameter 2: request path
			Parameter 3: asynchronous, true or false
		*/
		request.open("GET" ,"DemoServlet" ,true );
		request.send();
	}
If you want to get data while sending the request, the code is as follows:
	//Execute get request
	function get() {
		
		//1. Create xmlhttprequest object
		var request = ajaxFunction();
		
		//2. Send request (with parameters)
		request.open("GET" ,"DemoServlet?name=zhangsan&age=18" ,true );
		
		//3. Get response data [register to listen]. If the status of the preparation changes, the method to the right of the = sign is executed
		request.onreadystatechange = function(){
			
			if(request.readyState == 4 && request.status == 200){
				//Pop up response information
				alert(request.responseText);
			}
		}
		request.send();
	}

3.2 data request Post

<script type="text/javascript">

	//1. Create object
	function  ajaxFunction(){
	   var xmlHttp;
	   try{ // Firefox, Opera 8.0+, Safari
	        xmlHttp=new XMLHttpRequest();
	    }
	    catch (e){
		   try{// Internet Explorer
		         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		      }
		    catch (e){
		      try{
		         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		      }
		      catch (e){}
		      }
	    }
	
		return xmlHttp;
	 }
	
	function post() {
		//1. Create object
		var request = ajaxFunction();
		
		//2. Send request
		request.open( "POST", "DemoServlet", true );
	
		//If you don't have data, you can write this line
		//request.send();
		
		//If you want to bring data, write the following two lines
		
		//If you use post mode with data, you need to add a header here, indicating that the submitted data type is a url encoded form data
		request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		
		//In the past with data, write form data in the send method. 
		request.send("name=zhangsan&age=18");
	}

</script>
If you need to get data, the code is as follows
		function post() {
			//1. Create object
			var request = ajaxFunction();
			
			//2. Send request
			request.open( "POST", "DemoServlet", true );
			
			//Get data from server 
			request.onreadystatechange=function(){
				if(request.readyState==4 && request.status == 200){
				
					alert("post: "+request.responseText);
				}
			}
			
			request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			
			request.send("name=zhangsan&age=18");
		}

4. Implementation case: Ajax asynchronous verification user name

4.1 construction environment
1. Page preparation [demo.jsp]
<body>
   	<table border="1" width="500">
   		<tr>
   			<td>User name</td>
   			<td><input type="text" name="name" id="name"  onblur="checkUserName()"><span id="span01"></span></td> 
   		</tr>
   		<tr>
   			<td>Password</td>
   			<td><input type="text" name=""></td>
   		</tr>
   		<tr>
   			<td>mailbox</td>
   			<td><input type="text" name=""></td>
   		</tr>
   		<tr>
   			<td>brief introduction</td>
   			<td><input type="text" name=""></td>
   		</tr>
   		<tr>
   			<td colspan="2"><input type="submit" value="register"></td>
   		</tr>
   	</table>
   </body>
2. Database preparation

[Note: during the exercise, you can add multiple fields, mainly username]

4.2 Servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			
			request.setCharacterEncoding("UTF-8");
			
			//1. Check whether there is
			String name = request.getParameter("name");
			System.out.println("name="+name);
			
			UserDao dao = new UserDaomImpl();
			boolean isExist = dao.checkUserName(name);
			
			//2. Whether there is a notice page or not.
			if(isExist){
				response.getWriter().println(1);  //User name exists
			}else{
				response.getWriter().println(2); //The user name does not exist
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
}
4.3 Dao code
public class UserDaomImpl implements UserDao{

			@Override
			public boolean checkUserName(String username) throws SQLException {
				QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
				
				String sql = "select table(*) from t_user where username =?";


				runner.query(sql, new  ScalarHandler(), username);

				Long result = (Long) runner.query(sql, new  ScalarHandler(), username); 
				return result > 0 ;
			}
		
		}
4.4 jsp page display
function checkUserName() {

		//Get the value of the input box document the whole page
		var name = document.getElementById("name").value; // value  value() val val()
		//1. Create object
		var request = ajaxFunction();
		
		//2. Send request
		request.open("POST"  ,"CheckUserNameServlet" , true );
		
		//Register status change monitor to obtain the data transmitted by the server
		request.onreadystatechange = function(){
			
			if(request.readyState == 4 && request.status == 200){
				//alert(request.responseText);
				var data = request.responseText;
				if(data == 1){
					//Alert (user name already exists);
					document.getElementById("span01").innerHTML = "<font color='red'>User name already exists!</font>";
				}else{
					document.getElementById("span01").innerHTML = "<font color='green'>User name available!</font>";
					//alert("user name does not exist");
				}
			}
			
		}
		
		request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		request.send("name="+name);
	}

5. Supplement: synchronous and asynchronous

5.1 synchronization

Synchronization is to call something. The caller needs to wait for the result of the call to continue to execute later.

5.2 asynchronous

Asynchrony, contrary to synchronization, the caller will not get the result immediately, but after the call is sent, the caller can continue to perform subsequent operations.

Published 13 original articles, won praise 3, visited 668
Private letter follow

Tags: Javascript SQL xml Firefox

Posted on Wed, 05 Feb 2020 04:23:14 -0500 by ernielou