The best way to learn technology is to learn by doing , Make a little demo To verify the front-end input in real time .

utilize ajax Technology and Sevlet Technology to implement , Use native js.

The source code is accessible , my Github

What is? ajax

Ajax namely “Asynchronous Javascript And XML”( asynchronous JavaScript and XML), It refers to a web development technology for creating interactive web applications .

Ajax = asynchronous JavaScript and XML( A subset of Standard General Markup Languages ).

Ajax Is a technology for creating fast dynamic web pages .

Ajax It's a way to do this without reloading the entire web page , Technology to update some web pages .

Through a small amount of data exchange with the server in the background ,Ajax Asynchronous update of web pages . This means that you can load the entire page without reloading it , Update a part of the web page .

Traditional web pages ( Don't use Ajax) If you need to update the content , You have to reload the entire page .

This is Baidu's definition of it , Enough detail .

One thing worth adding is the understanding of asynchrony , Asynchrony is relative to synchronization , Here they refer to the interaction mode between the server and the browser .

Sync , After each request , User actions are blocked , You must request that you return a response and continue . Asynchrony is when a request is made , Users don't have to wait for a response , All by ajax To achieve , The data can be updated locally without refreshing the web page . It improves the communication efficiency between the two sides .

A little demo

Make a validation form without refreshing demo, Enter the user name in the dialog box , Verify in the background , Use ajax technology .

Project structure , Use maven structure



login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>login</title>
</head>
<body> Welcome landing :
user name :<input type="text" name="username" id="username" onchange="CallServer()"/> <!-- Display prompt message -->
<div id="msg"></div> <!-- stay jsp Page in js, The way of absolute path -->
<script src="${pageContext.request.contextPath}/js/main.js"></script> </body>
</html>

main.js


alert("use ajax!") // establish XMLHttpRequest object , In different browsers
function createXMLHTTP() {
if(window.XMLHttpRequest){
// IE7+, Firefox, Chrome, Opera, Safari Browser execution code
xmlhttp = new XMLHttpRequest();
}else {
// IE6, IE5 Browser execution code
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
} function CallServer() {
var username = document.getElementById("username").value;
// The judgment is empty
if ((username == null) || (username == "")) return; var xmlhttp = createXMLHTTP(); // Build request url
var url = "/loginServlet"+"?"+"username="+username; // The status code changes the call event
xmlhttp.onreadystatechange = function () {
// Normal return , Replace msg Content
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("msg").innerHTML = xmlhttp.responseText;
}
}
// Submit requests asynchronously
xmlhttp.open("GET",url,true);
// Send a request
xmlhttp.send();
}

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.lbw.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>

loginServlet.java

package com.lbw.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; /**
* The back-end using Servlet Processing requests
*/
public class loginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the encoding and response header
request.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
// To obtain parameters
String username = request.getParameter("username"); String msg = ""; if("lbw".equals(username)){
msg = " The name is correct ";
}else {
msg = " Name error ";
}
PrintWriter out = response.getWriter();
out.println(msg);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}

Start testing

Input localhost:8888/login.jsp, Pop-up window



On behalf of the jsp Introduction in js success

Enter the test data in the input box



from Servlet Logic determines , Return error message



from Servlet Logic determines , Return success message

thus , Preliminary realization ajax Asynchronous requests , It meets the requirements of real-time verification

Some small details

  1. In the use of maven Build the project , Be careful Project Structure -> Facets, Set up here web.xml and webapp The path of ,idea Will use
  2. In the introduction of js when , Note the use of relative paths for mapping , And use EL Expression to open isELIgnored="false"·` Avoid not parsing .

ajax On -- Implementation of simple real-time verification of more related articles

  1. AJAX+jQuery+ASP Realize real-time verification of ID card information --- Personnel system

    A lot of times when you register on a website , We will find that , Registration forms usually need to check the availability of user names and e-mail addresses : To ensure that users don't have the same user name and email address : Some websites like when users submit user information , Check the availability of information , And one ...

  2. AJAX On ,XMLHttpRequest Introduce

    AJAX On ,XMLHttpRequest Introduce AJAX      AJAX = Asynchronous JavaScript and XML. Asynchronous JavaScript and XML.      AJ ...

  3. 【ADO.NET】2、 Various versions of Simple login verification

    One . Simple login verification ( prevent SQL Inject ) GetString( Serial number ) Returns the value of a column ( When the user doesn't remember the column name number , You can use GetOrdinal() Get the serial number )GetInt32( Serial number ) Aiming at int Field , return i ...

  4. jquery Form real time validation

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. WebService Simple security verification

    original text :WebService Simple security verification Recently, there is a new one that needs to call a third party WebService Project , Seeing this third party WebService When called , You need an authorized user name and password , So I also want to WebServic ...

  6. MVC verification 09- Use MVC Of Ajax.BeginForm Method to implement asynchronous verification

    original text :MVC verification 09- Use MVC Of Ajax.BeginForm Method to implement asynchronous verification MVC in , There are several ways to submit to the background : 1.Html.BeginForm(): Sync 2.Ajax.BeginForm(): different ...

  7. Bitcoin block structure Merkle Tree and simple payment verification analysis

    In the bitcoin network , Not every node has the ability to store complete blockchain data , Limited by storage space , Many nodes are based on SPV(Simplified Payment Verification Simple payment verification ) Wallet connected to bitcoin network , through ...

  8. django On - Create a simple blogging system

    django First step 1. django install pip install django print(django.get_version()) see django edition 2. Create project open cmd, Enter the specified directory ...

  9. django On - Create a simple blogging system ( Two )

    Part 1 django On - Create a simple blogging system ( One ) It has been recorded Django The whole process of blog publishing , Next, we will continue to explain the display of blog title and content . Show blog details Saving blog content to a database is not the ultimate goal of blogging , Blog 1 ...

Random recommendation

  1. 【 code 】_C# Code name in (Name) And page identification (CodePage) The relationship between _ code gb2312 Acquisition

    Writing C# Code , Find out VS Offer not directly offer gb2312 The Chinese code of , therefore , You need to find the corresponding encoding name codepage To call the desired encoding . Here's all the coding information provided by Microsoft programming , Including the code name , Code page identifier , ...

  2. Use Java Pure code implementation MySQL The connection of

      Building a database 1.  Click to connect -->MySQL: Enter the connection name . Host name /IP Address . port . user name . password ( Omit without a password ), Then click OK , The established table is gray, indicating the closed state , Double click to open 2.  Recreate ...

  3. java Release web project

    Java Web Project release process One . Basic conditions jdk tomcat Two . Operation steps 4. Generate war package :Eclipse: Right click on the item ->Export->WAR file, Such as :hello.war 4 ...

  4. NVelocity-0.4.2.8580 Modification record [ Send out vs2008 Available versions ] -- &quot;It appears that no class was specified as the ResourceManager...&quot; bug Amendments, etc

    Because there are other development record tools that are not very up-to-date cnblog Write Development Notes . But I think this is a serious problem , I think it's necessary to let more people know how to deal with it , So in cnblog I hope it will be widely spread . Because now on the Internet vs200 ...

  5. Java Day 06

    Two dimensional array   Definition :  Format 1 int[][] arr = new int[3][2];  Format 2 int[][] arr = new int[3][];// Each one-dimensional array is initialized as null Null pointer exception Format 3 ...

  6. For a website , How to prohibit direct access from the browser Web browser Medium visit js file

    For example, there is a website ,https://testsystem.infotest.com Under the content file directory of this website , There is one scripts Folder , There is a... In this folder js file , such as lukeTest.js file such ...

  7. linux File name garbled solution

    1.linux Decompress the garbled files unzip -O CP936 xxx.zip 2. The general document uses convmv sudo convmv -f gbk -t utf-8 -r --notest /your_d ...

  8. python + seleinum +phantomjs Set up headers and proxy agent

    python + seleinum +phantomjs Set up headers and proxy agent     Recently, because work needs to use selenium+phantomjs Headless browser , There were some holes in it , Make a note of , especially ...

  9. [ Environmental Science ]vscode in python A virtual environment

    In the project .vscode/settings.json Lower setup { "python.pythonPath": "/path/to/python2.7"}

  10. python Data type three ( Dictionaries )

    One . Introduction to the dictionary Dictionaries (dict) yes python The only mapping type in , It is a {} The enclosed key value pairs consist of , stay dict in key Is the only one. , At the time of preservation , according to key To calculate a memory address , And then key-value preservation ...