current position:Home>【Java WEB】AJAX

【Java WEB】AJAX

2022-04-29 16:40:11Hello Code.

Personal blog :www.hellocode.top
All articles are in Top blog First episode , Other platforms update synchronously
This column :《Java Web From introduction to practice 》
If not Java Basics , Please go to 《Java Zero basis guide 》 Column to learn the corresponding knowledge
If there is a problem , Welcome to correct , Learning together ~~



  • AJAX(Asynchronous JavaScript And XML): asynchronous Of JavaScript and XML
  • It's not a new technology in itself , It's a combination of multiple technologies , Technology for quickly creating dynamic web pages
  • If you need to update the content of a general web page , You have to reload the entire page
  • and AJAX A small amount of data exchange with the server through the browser , You can make web pages update asynchronously . That is, without reloading the entire page , Part of the content of the web page Partial update

Quick start

Native JavaScript Realization AJAX

  • The core object :XMLHttpRequest
    Used to exchange data with the server in the background . You can do this without reloading the entire web page , Update a part of the web page
  • Open the link :open(method,url,async)
    method: Type of request (GET or POST)
    url: The path of the request resource
    async:true( asynchronous ) or false( Sync )
  • Send a request :send(String params)
    params: Requested parameters (POST special )
  • Process response :onreadystatechange
    readyState:0- Request not initialized ,1- Server connection established ,2- Request accepted ,3- Request processing ,4- Request completed , And the response is ready
    status:200- Response completed OK
  • Obtain the corresponding data form
    responseText: Get response data as a string
    responseXML: get XML Response data in form
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> User registration </title>
</head>
<body>
    <form autocomplete="off">
         full name :<input type="text" id="username">
        <span id="uSpan"></span>
        <br>
         password :<input type="password" id="password">
        <br>
        <input type="submit" value=" register ">
    </form>
</body>
<script> //  Lose focus event for name binding  document.getElementById("username").onblur = function (){
       //  establish XMLHttpRequest The core object  let xmlHttp = new XMLHttpRequest(); //  Open the link  let username = document.getElementById("username").value; xmlHttp.open("GET","/userServlet?username=" + username,true); //  Send a request  xmlHttp.send(); //  Process response  xmlHttp.onreadystatechange = function (){
       //  conditional , Whether the request and response are successful  if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
       //  Display the data of the response to span In the label  document.getElementById("uSpan").innerHTML = xmlHttp.responseText; } } } </script>
</html>
package study.ajax;

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;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        //  Set the garbled code of request and response 
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //  Get request parameters 
        String username = req.getParameter("username");

        //  Determine whether the name is registered 
        if("zhangsan".equals(username)){
    
            resp.getWriter().write("<font color = 'red'> The user name is registered </font>");
        }else{
    
            resp.getWriter().write("<font color = 'green'> User name available </font>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        doGet(req,resp);
    }
}

jQuery Of GET How to achieve AJAX

  • Core grammar :$.get(url,[data],[callback],[type]);
    url: The requested resource path
    data: The request parameters sent to the server , The format can be key=value, It can also be js object
    callback: The callback function after the request is successful , We can write our logic code in functions
    type: Expected return data type , The value can be xml,html,js,json,text etc.
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> User registration </title>
</head>
<body>
    <form autocomplete="off">
         full name :<input type="text" id="username">
        <span id="uSpan"></span>
        <br>
         password :<input type="password" id="password">
        <br>
        <input type="submit" value=" register ">
    </form>
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script> //  Bind out of focus event for user name  $("#username").blur(function (){
       let username = $("#username").val(); // jQuery Of GET  How to achieve  AJAX $.get( //  The requested resource path  "userServlet", //  Requested parameters  "username=" + username, //  Callback function  function (data){
       //  Display the data of the response to span On the label  $("#uSpan").html(data); }, //  Response data form  "text" ) }); </script>
</html>

Corresponding Java Processing code and JS The native processing code is consistent

jQuery Of POST How to achieve AJAX

  • Core grammar :$.post(url,[data],[callback],[type]);
    url: The requested resource path
    data: The request parameters sent to the server , The format can be key=value, It can also be js object
    callback: The callback function after the request is successful , We can write our logic code in functions
    type: Expected return data type , The value can be xml,html,js,json,text etc.
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> User registration </title>
</head>
<body>
    <form autocomplete="off">
         full name :<input type="text" id="username">
        <span id="uSpan"></span>
        <br>
         password :<input type="password" id="password">
        <br>
        <input type="submit" value=" register ">
    </form>
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script> //  Bind out of focus event for user name  $("#username").blur(function (){
       let username = $("#username").val(); // jQuery Of POST  How to achieve  AJAX $.post( //  The requested resource path  "userServlet", //  Requested parameters  "username=" + username, //  Callback function  function (data){
       //  Display the data of the response to span On the label  $("#uSpan").html(data); }, //  Response data form  "text" ) }); </script>
</html>

post and get Way just $.post and $.get Different method names , Other parameters are consistent

jQuery A common way to achieve AJAX

  • Core grammar :$.ajax({name:value,name:value,...});
    • url: The requested resource path
    • async: Asynchronous request or not ,true- yes ,false- no ( Default )
    • data: The request parameters sent to the server , The format can be key=value, It can also be js object
    • type: Request mode ,POST or GET( The default is GET)
    • dataType: Expected return data type , The value can be xml,html,js,json,text etc.
    • success: Callback function called when the request is successful
    • error: Callback function called when the request fails
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> User registration </title>
</head>
<body>
    <form autocomplete="off">
         full name :<input type="text" id="username">
        <span id="uSpan"></span>
        <br>
         password :<input type="password" id="password">
        <br>
        <input type="submit" value=" register ">
    </form>
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script> //  Bind out of focus event for user name  $("#username").blur(function (){
       let username = $("#username").val(); // jQuery A common way to achieve  AJAX $.ajax({
       //  Request resource path  url:"userServlet", //  Asynchronous or not  async:true, //  Request parameters  data:"username="+username, //  Request mode  type:"GET", //  Return the response data form  dataType:"text", // Callback function after successful request  success:function (data){
       $("#uSpan").html(data); }, //  Callback function for request failure  error:function (){
       alert(" operation failed "); } }) }); </script>
</html>

JSON To deal with

Basic introduction

  • JSON(JavaScript Object Notation): Is a lightweight data exchange format
  • It is based on ECMAScript A subset of the specification , Use text format completely independent of programming language to store and represent data
  • The concise and clear hierarchy makes JSON Become the ideal data exchange language . Easy to read and write , At the same time, it is also easy to calculate, analyze and generate , And effectively improve the network transmission efficiency
  • Create format
    type grammar explain
    object type {name:value,name:value,…}name It's a string type ,value It can be any type
    Array / Collection types [{name:value,…},{name:value,…}]name It's a string type ,value It can be any type
    Mixed type {name:
    [{name:value,…},{name:value,…}]
    }
    name It's a string type ,value It can be any type
  • Common methods
    Member method explain
    stringify( object ) Converts the specified object to json Format string
    parse( character string ) Will specify json The format string is parsed into an object

Transformation tool

  • In addition to the JavaScript Use in JSON Outside , stay Java Can also be used in JSON
  • JSON The conversion tool is through Java Well encapsulated jar tool kit
  • Can be Java Convert an object or collection to JSON Format string , Can also be JSON Format string to Java object
  • Jackson: Open source free JSON Transformation tool ,SpringMVC Conversion defaults to Jackson

step

  1. Import jar package
  2. Create core objects
  3. Call the method to complete the conversion

Common classes

Class name explain
ObjectMapper yes Jackson The core class of the toolkit , It provides some ways to implement JSON Conversion between strings and objects
TypeReference Deserialization of collection generics , Use TypeReference You can explicitly specify the object type of deserialization
  • ObjectMapper Common methods
    Method name explain
    String writeValueAsString(Object obj) take Java Object to JSON character string
    <T> T readValue(String json, Class<T> valueType) take JSON String conversion to Java object
    <T> T readValue(String json, TypeReference valueTypeRef) take JSON String conversion to Java object

Conversion exercise

  1. Object turn JSON,JSON Transfer object
  2. Map<String,String> turn JSON,JSON turn Map<String,String>
  3. Map<String,User> turn JSON,JSON turn Map<String,User>
  4. List<String> turn JSON,JSON turn List<String>
  5. List<User> turn JSON,JSON turn List<User>
package study.ajax02;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ObjectMapperTest {
    
    private ObjectMapper mapper = new ObjectMapper();

    //  Object turn  JSON,JSON  Transfer object 
    @Test
    public void test01() throws Exception {
    
        // User  turn  json
        User user = new User(" Zhang San ", 23);
        String json = mapper.writeValueAsString(user);
        System.out.println("json  character string :" + json);

        // json  turn  User
        User user2 = mapper.readValue(json, User.class);
        System.out.println("java object :" + user2);
    }

    // Map<String,String>  turn  JSON, JSON  turn  Map<String,String>
    @Test
    public void test02() throws Exception {
    
        // Map<String,String>  turn  JSON
        HashMap<String, String> map = new HashMap<>();
        map.put(" full name ", " Zhang San ");
        map.put(" Gender ", " male ");
        String json = mapper.writeValueAsString(map);
        System.out.println("json  character string :" + json);

        // JSON  turn  Map<String,String>
        HashMap<String, String> map2 = mapper.readValue(json, HashMap.class);
        System.out.println("java object :" + map2);
    }

    // Map<String,User> turn JSON,JSON  turn Map<String,User>
    @Test
    public void test03() throws Exception {
    
        // Map<String,User> turn JSON
        HashMap<String, User> map = new HashMap<>();
        map.put(" Class one ", new User(" Zhang San ", 23));
        map.put(" Class two ", new User(" Li Si ", 24));
        String json = mapper.writeValueAsString(map);
        System.out.println("json  character string :" + json);

        // JSON  turn Map<String,User>
        HashMap<String, User> map2 = mapper.readValue(json, new TypeReference<HashMap<String, User>>() {
    
        });
        System.out.println("java object :" + map2);

    }

    // List<String> turn  JSON,JSON turn  List<String>
    @Test
    public void test04() throws Exception {
    
        // List<String> turn  JSON
        ArrayList<String> list = new ArrayList<>();
        list.add(" Zhang San ");
        list.add(" Li Si ");
        String json = mapper.writeValueAsString(list);
        System.out.println("json  character string :" + json);

        // JSON turn  List<String>
        ArrayList<String> list2 = mapper.readValue(json, ArrayList.class);
        System.out.println("java object :" + list2);
    }

    // List<User> turn  JSON,JSON turn  List<User>
    @Test
    public void test05() throws Exception {
    
        // List<User> turn  JSON
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(" Zhang San ",23));
        list.add(new User(" Li Si ",24));
        String json = mapper.writeValueAsString(list);
        System.out.println("json  character string :" + json);

        // JSON turn  List<User>
        ArrayList<User> list2 = mapper.readValue(json, new TypeReference<ArrayList<User>>() {
    
        });
        System.out.println("java object :" + list2);

    }
}

Comprehensive case

Search Lenovo

  • Data preparation
    CREATE TABLE USER(
    	id INT PRIMARY KEY AUTO_INCREMENT,
    	NAME VARCHAR(20),
    	age INT,
    	search_count INT	--  Number of searches 
    );
    
    INSERT INTO USER VALUES 
    (NULL," Zhang San ",23,25),(NULL," Li Si ",24,5),(NULL," Wang Wu ",25,3),
    (NULL," Zhao Liu ",26,7),(NULL," Zhang Sanfeng ",93,20),(NULL," zhang wuji ",18,23),
    (NULL," Zhang Qiang ",33,21),(NULL," Zhang Guolao ",65,6);
    
    # config.properties
    
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://192.168.23.129:3306/db13
    username=root
    password= password 
    
    # log4j.properties
    
    # Global logging configuration
    #  Display of output information . Four levels :ERROR、WARN、INFO、DEBUG
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    
    <!--MyBatisConfig.xml-->
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis Of DTD constraint -->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <!-- The core root tag -->
    <configuration>
        <!--  Import database connection information configuration file  -->
        <properties resource="config.properties"/>
        <!-- Integrate LOG4J Log information -->
        <settings>
            <setting name="logImpl" value="log4j"/>
        </settings>
        <!-- Configure the database environment , There can be multiple environments .default Specify which is used -->
        <environments default="mysql">
            <!-- Configure the database environment , You can write many ,id Represents a unique identifier -->
            <environment id="mysql">
                <!-- Business management ,type Attribute represents the use of JDBC Default transaction -->
                <transactionManager type="JDBC"></transactionManager>
                <!-- Data source information ,type Property represents the connection pool -->
                <dataSource type="POOLED">
                    <!-- Get the configuration information of the database connection -->
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
        <!-- Import mapping profile -->
        <mappers>
            <!-- The package where the interface is located -->
            <package name="study.ajax.mapper"/>
        </mappers>
    </configuration>
    
  • page
    1. Bind the mouse click event to the user name input box
    2. Get the entered user name data
    3. Judge whether the user name is empty
    4. If it is empty , Hide the association prompt box
    5. If it's not empty , Then send AJAX request , And display the response data to the association box
  • The server
    1. Get request parameters
    2. Call the fuzzy query method of the business layer
    3. Convert the returned data to JSON, And respond to the client

copyright notice
author[Hello Code.],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204291640061019.html

Random recommended