AJAX_ Introduction & classic cases

AJAX_ Introduction & classic cases Getting started with AJAX AJAX introduction AJAX(Asynchronous JavaScript And...
Getting started with AJAX
JSON processing
Comprehensive case search Association
Comprehensive case paging
AJAX_ Introduction & classic cases

Getting started with AJAX

AJAX introduction

  • AJAX(Asynchronous JavaScript And XML): asynchronous JavaScript and XML.
  • It is not a new technology in itself, but a combination of multiple technologies. Technology for quickly creating dynamic web pages.
  • If you need to update the content of a normal web page, you must reload pages.
  • AJAX can update web pages asynchronously by exchanging a little data between browser and server. That is to say, the partial content of the web page is updated without reloading the whole page.

  • asynchronous
  • synchronization

Native JavaScript implementation of AJAX

  • Core object: XMLHttpRequest
    Used to exchange data with the server in the background. You can update a part of a page without reloading the entire page.
  • Open link: open(method,url,async)
    method: the type of request GET or POST.
    url: the path of the request resource.
    async: true (asynchronous) or false (synchronous).
  • Send request: send(String params)
    params: the parameter of the request (special for POST).
  • Processing response: onreadystatechange
    readyState: 0-request uninitialized, 1-server connection established, 2-request received, 3-request processing, 4-request completed and response ready.
    status: 200 - all responses are OK.
  • Get response data form
    responseText: get the response data in the form of string.
    Response XML: get the response data in XML form.

code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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> //1. Binding lost focus event for name document.getElementById("username").onblur = function() { //2. Create XMLHttpRequest core object let xmlHttp = new XMLHttpRequest(); //3. Open the link let username = document.getElementById("username").value; xmlHttp.open("GET","userServlet?username="+username,true); //xmlHttp.open("GET","userServlet?username="+username,false); //4. Send request xmlHttp.send(); //5. Handling response xmlHttp.onreadystatechange = function() { //Judge whether the request and response are successful if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { //Display the data of the response to the span tab document.getElementById("uSpan").innerHTML = xmlHttp.responseText; } } } </script> </html>

Page effect:

servlet Code:

package com.itheima01; 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 request and response garbled req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); //1. Get request parameters String username = req.getParameter("username"); //The simulation server takes 5 seconds to process the request /*try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }*/ //2. Judge whether the name has been registered if("zhangsan".equals(username)) { resp.getWriter().write("<font color='red'>User name 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); } }

GET mode of jQuery to implement AJAX

  • Core syntax: $. get(url,[data],[callback],[type]);
    url: the resource path of the request.
    data: the request parameter sent to the server. The format can be key=value or js object.
    Callback: the callback function after the request is successful. We can write our logic code in the function.
    Type: the expected return data type. The values can be xml, html, js, json, text, etc.

code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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.3.1.min.js"></script> <script> //1. Binding lost focus event for user name $("#username").blur(function () { let username = $("#username").val(); //2. AJAX is implemented in GET mode of jquery $.get( //Requested resource path "userServlet", //Request parameters "username=" + username, //Callback function function (data) { //Display the data of the response to the span tab $("#uSpan").html(data); }, //Response data form "text" ); }); </script> </html>

jQuery's POST implementation of AJAX

  • Core syntax: $. post(url,[data],[callback],[type]);
    url: the resource path of the request.
    data: the request parameter sent to the server. The format can be key=value or js object.
    Callback: the callback function after the request is successful. We can write our logic code in the function.
    Type: the expected return data type. The values can be xml, html, js, json, text, etc.

code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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.3.1.min.js"></script> <script> //1. Binding lost focus event for user name $("#username").blur(function () { let username = $("#username").val(); //2.jQuery's POST implementation of AJAX $.post( //Requested resource path "userServlet", //Request parameters "username=" + username, //Callback function function (data) { //Display the data of the response to the span tab $("#uSpan").html(data); }, //Response data form "text" ); }); </script> </html>

The general way to implement AJAX in jQuery

  • Core syntax: $. ajax(;
    url: the resource path of the request.
    async: asynchronous request or not, true yes, false no (the default is true).
    Data: the data sent to the server can be in the form of key value pair or js object.
    type: request method, POST or GET (GET by default).
    dataType: the expected type of returned data. The values can be xml, html, js, json, text, etc.
    success: the callback function that is called when the request is successful.
    error: the callback function called when the request fails.

code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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.3.1.min.js"></script> <script> //1. Binding lost focus event for user name $("#username").blur(function () { let username = $("#username").val(); //2. The general way of jQuery to implement AJAX $.ajax({ //Request resource path url:"userServlet", //Asynchronous or not async:true, //Request parameters data:"username="+username, //Request method type:"POST", //Data form dataType:"text", //Callback function called after successful request success:function (data) { //Display the data of the response to the span tab $("#uSpan").html(data); }, //Callback function invoked after request failed error:function () { alert("operation failed..."); } }); }); </script> </html>

AJAX quick start summary

  • AJAX(Asynchronous JavaScript And XML): asynchronous JavaScript and XML.
  • Through a small amount of data exchange between browser and server, web pages can be updated asynchronously. That is to say, the partial content of the web page is updated without reloading the whole page.
  • Synchronous and asynchronous
    Synchronization: the server cannot perform other operations during processing.
    Asynchrony: the server can perform other operations during processing.
  • GET mode implementation: $. get();
  • POST mode implementation: $. post();
    url: the resource path of the request.
    data: the request parameter sent to the server. The format can be key=value or js object.
    Callback: the callback function after the request is successful. We can write our logic code in the function.
    Type: the expected return data type. The values can be xml, html, js, json, text, etc.
  • Common way to implement: $. ajax();
    url: the resource path of the request.
    async: asynchronous request or not, true yes, false no (the default is true).
    Data: the data sent to the server can be in the form of key value pair or js object.
    type: request method, POST or GET (GET by default).
    dataType: the expected type of returned data. The values can be xml, html, js, json, text, etc.
    success: the callback function that is called when the request is successful.
    error: the callback function called when the request fails.

JSON processing

JSON review

  • JSON(JavaScript Object Notation): is a lightweight data exchange format.
  • It is based on a subset of ECMAScript specification and uses a text format completely independent of programming language to store and represent data.
  • The simple and clear hierarchy makes JSON an ideal data exchange language. Easy to read and write, but also easy to computer analysis and generation, and effectively improve the efficiency of network transmission.
  • Create format
  • common method

JSON conversion tool

  • In addition to using JSON in JavaScript, we can also use JSON in JAVA.
  • The transformation tools of JSON are some JAR toolkits encapsulated by JAVA.
  • You can convert JAVA objects or collections to strings in JSON format, or you can convert strings in JSON format to JAVA objects.
  • Jackson: open source and free JSON conversion tool. Jackson is used by default for spring MVC conversion
    1. Import the jar package.
    2. Create core objects.
    3. Call the method to complete the conversion.
  • Common classes
  • Common methods of ObjectMapper

json conversion code:
User class:

package com.itheima02; public class User { private String name; private Integer age; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }

Test class:

package com.itheima02; 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; /* JSON Use of conversion tools */ public class ObjectMapperTest { private ObjectMapper mapper = new ObjectMapper(); /* 1.User Object to json, json to User object json String = {"name": "Zhang San", "age":23} user Object = User */ @Test public void test01() throws Exception{ //User object to json User user = new User("Zhang San",23); String json = mapper.writeValueAsString(user); System.out.println("json character string:" + json); //json to User object User user2 = mapper.readValue(json, User.class); System.out.println("java Object:" + user2); } /* 2.map<String,String>Turn JSON, turn JSON to map < string, string > json String = {"name": "Zhang San", "gender": "male"} map Object = */ @Test public void test02() throws Exception{ //Map < string, string > to 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 to map < string, string > HashMap<String,String> map2 = mapper.readValue(json, HashMap.class); System.out.println("java Object:" + map2); } /* 3.map<String,User>Turn JSON to map < string, user > json String = {"black horse class 1": {"name": "Zhang San", "age":23}, "black horse class 2": {"name": "Li Si", "age":24}}} map Object = , black horse class 2 = User}} */ @Test public void test03() throws Exception{ //Map < string, user > to 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 to map < string, user > //HashMap<String,User> map2 = mapper.readValue(json,new TypeReference<HashMap<String,User>>(){}); HashMap<String,User> map2 = mapper.readValue(json, new TypeReference<HashMap<String, User>>() { }); System.out.println("java Object:" + map2); } /* 4.List<String>Turn JSON to list < string > json String = ["Zhang San", "Li Si"] list Object = [Zhang San, Li Si] */ @Test public void test04() throws Exception{ //List < string > to 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 to list < string > ArrayList<String> list2 = mapper.readValue(json,ArrayList.class); System.out.println("java Object:" + list2); } /* 5.List<User>Turn JSON to list < user > json String = [{"name": "Zhang San", "age":23},{"name": "Li Si", "age":24}] list Object = [User, User] */ @Test public void test05() throws Exception{ //List < user > to 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 to list < user > // ArrayList<User> list2 = mapper.readValue(json,new TypeReference<ArrayList<User>>(){}); ArrayList<User> list2 = mapper.readValue(json, new TypeReference<ArrayList<User>>() { }); System.out.println("java Object:" + list2); } }

Summary of JSON processing

  • Jackson: open source and free JSON conversion tool. By default, Jackson is used for spring MVC conversion.
  • You can convert JAVA objects or collections to strings in JSON format, or you can convert strings in JSON format to JAVA objects.
  • Common classes
  • Common methods of ObjectMapper

Comprehensive case search Association

Case effect

Environmental preparation

  • Using Mysql database
-- establish db10 database CREATE DATABASE db10; -- use db10 database USE db10; -- establish user surface CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, -- Primary key id NAME VARCHAR(20), -- full name age INT, -- Age search_count INT -- Number of searches ); -- Insert test data 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);

Case analysis and Implementation

  • 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, the association prompt box will be hidden.
    5. If it is not empty, send the AJAX request and display the response data to the Lenovo box.
  • Control layer
    1. Get the request parameters.
    2. Call the fuzzy query method of the business layer.
    3. Convert the returned data to JSON and respond to the client.

code:
User class:

package com.itheima.bean; /* User's entity class */ public class User { private Integer id; // Primary key id private String name; // full name private Integer age; // Age private Integer search_count; //Number of searches public User() { } public User(Integer id, String name, Integer age, Integer search_count) { this.id = id; this.name = name; this.age = age; this.search_count = search_count; } public Integer getSearch_count() { return search_count; } public void setSearch_count(Integer search_count) { this.search_count = search_count; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }

Control layer (servlet):

package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.bean.User; import com.itheima.service.UserService; import com.itheima.service.impl.UserServiceImpl; 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.util.List; @WebServlet("/userServlet") public class UserServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Set the encoding of requests and responses req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); //1. Get request parameters String username = req.getParameter("username"); //2. Call the fuzzy query method of business layer to get data UserService service = new UserServiceImpl(); List<User> users = service.selectLike(username); //3. Convert the data to JSON and respond to the client ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(users); resp.getWriter().write(json); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }

Business layer:

package com.itheima.service.impl; import com.itheima.bean.User; import com.itheima.mapper.UserMapper; import com.itheima.service.UserService; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; public class UserServiceImpl implements UserService { @Override public List<User> selectLike(String username) { List<User> users = null; SqlSession sqlSession = null; InputStream is = null; try { //Load core profile is = Resources.getResourceAsStream("MyBatisConfig.xml"); //Get sqlSession factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //Get sqlSession object sqlSession = sqlSessionFactory.openSession(true); //Get the implementation class object of UserMapper UserMapper mapper = sqlSession.getMapper(UserMapper.class); //Call the fuzzy query method of implementation class users = mapper.selectLike(username); } catch (IOException e) { e.printStackTrace(); }finally { //Release resources if(sqlSession != null){ sqlSession.close(); } if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //Return results to control layer return users; } }

DAO layer (UserMapper):

package com.itheima.mapper; import com.itheima.bean.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { /* Fuzzy query */ @Select("SELECT * FROM USER WHERE name LIKE CONCAT('%',#,'%') ORDER BY search_count DESC LIMIT 0,4") public abstract List<User> selectLike(String username); }

html page:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User search</title> <style type="text/css"> .content { width: 643px; margin: 100px auto; text-align: center; } input[type='text'] { width: 530px; height: 40px; font-size: 14px; } input[type='button'] { width: 100px; height: 46px; background: #38f; border: 0; color: #fff; font-size: 15px } .show { position: absolute; width: 535px; height: 100px; border: 1px solid #999; border-top: 0; display: none; } </style> </head> <body> <form autocomplete="off"> <div> <img src="img/logo.jpg"> <br/><br/> <input type="text" id="username"> <input type="button" value="Search for it"> <!--Data used to display Association--> <div id="show"></div> </div> </form> </body> <script src="js/jquery-3.3.1.min.js"></script> <script> //1. Bind mouse click event for user name input box $("#username").mousedown(function () { //2. Get the user name entered by the user let username = $("#username").val(); //3. Judge whether the user name is empty if(username == null || username == ""){ //4. If it is empty, hide the association box $("#show").hide(); return; } //5. If it is not empty, send an ajax request and display the data in the association box $.ajax({ //Requested resource path url:"userServlet", //Request parameters data:{"username":username}, //Request method type:"POST", //Response data type dataType:"json", //Callback function after successful response success:function (data) { //Display the returned data in the div of show let names = ""; for(let i = 0; i < data.length; i++){ names += "<div>"+data[i].name+"</div>"; } $("#show").html(names); $("#show").show(); } }) }) </script> </html>

Comprehensive case paging

Waterfall flow infinite load data paging

  • Case effect
  • Environmental preparation
    Using Mysql database
-- establish db11 database CREATE DATABASE db11; -- use db11 database USE db11; -- Create data table CREATE TABLE news( id INT PRIMARY KEY AUTO_INCREMENT, -- Primary key id title VARCHAR(999) -- News headlines ); -- insert data DELIMITER $$ CREATE PROCEDURE create_data() BEGIN DECLARE i INT; SET i=1; WHILE i<=100 DO INSERT INTO news VALUES (NULL,CONCAT('Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to be "based on reality"',i)); SET i=i+1; END WHILE; END $$ -- Call stored procedure CALL create_data();

Case analysis

  • How to make sure that the currently displayed data has been browsed?
    Formula: (distance between the scroll bar and the bottom + distance between the scroll bar and the current window) > = height of the current document
    Current document height: store 10 pieces of data, 100px.
    Distance from scroll bar to bottom: 1px.
    Height of current window: 80px.
    Scroll bar up and down the distance: > = 19px.
  • Prior knowledge

Case realization

  • page
    1. Define the send request flag.
    2. Define the current page number and the number of bars displayed per page.
    3. Define the distance from the bottom of the scroll bar.
    4. Set the page load event.
    5. Bind scrollbar scrolling events to the current window.
    6. Obtain necessary information (the height of the current window, the distance of scrolling up and down the scroll bar, and the height of the current document).
    7. Calculate whether the current display data has been browsed.
    8. Judge whether the request tag is true.
    9. Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed.
    10. Request to query the paging data according to the current page and the number of entries displayed on each page.
    11. Current page number + 1.
  • The server
    1. get the request parameters (current page, number of items displayed per page).
    2. According to the current Page number and the number of items displayed on each Page, call the method of the business layer to get the paging Page object.
    3. Convert the data to json.
    4. Respond the data to the client.

code:
News class:

package com.itheima.bean; /* News entities */ public class News { private Integer id; //Primary key id private String title; //News headlines public News() { } public News(Integer id, String title) { this.id = id; this.title = title; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }

Control layer NewsServlet class:

package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.pagehelper.Page; import com.itheima.service.NewsService; import com.itheima.service.impl.NewsServiceImpl; 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("/newsServlet") public class NewsServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Set the encoding of requests and responses req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); //Get request parameters String start = req.getParameter("start"); String pageSize = req.getParameter("pageSize"); //Call the query method of the business layer according to the current parameters to get the paging page object NewsServiceImpl service = new NewsServiceImpl(); Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize)); //Convert the data to json String json = new ObjectMapper().writeValueAsString(page); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //Corresponding data to customers resp.getWriter().write(json); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }

Business layer service class:

package com.itheima.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.mapper.NewsMapper; import com.itheima.service.NewsService; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class NewsServiceImpl implements NewsService { @Override public Page pageQuery(Integer start, Integer pageSize) { InputStream is = null; SqlSession sqlSession = null; Page page = null; try{ //1. Load core configuration file is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2. Get SqlSession factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3. Get SqlSession object through SqlSession factory object sqlSession = sqlSessionFactory.openSession(true); //4. Get the implementation class object of NewsMapper interface NewsMapper mapper = sqlSession.getMapper(NewsMapper.class); //5. Package Page object start: current Page pageSize: number of pieces displayed per Page page = PageHelper.startPage(start,pageSize); //6. Call all the query methods to implement class objects. At this time, the bottom layer executes MySQL limit paging query statement mapper.selectAll(); } catch (Exception e) { e.printStackTrace(); } finally { //7. Release resources if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //8. Return the page object to the control layer return page; } }

DAO layer NewsMapper class:

package com.itheima.mapper; import com.itheima.bean.News; import org.apache.ibatis.annotations.Select; import java.util.List; public interface NewsMapper { /* Query all */ @Select("SELECT * FROM news") public abstract List<News> selectAll(); }

html page:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Homepage</title> <link rel="stylesheet" href="css/tt.css"> </head> <body> <div> <span>download APP</span> <span> Beijing a sunny day</span> <span>More products</span> </div> <div> <div> <a> <img src="img/logo.png"><br/> </a> <ul> <li> <a href="#"> <span> recommend </span> </a> </li> <li><a href="#"> <span> video </span> </a></li> <li><a href="#"> <span> hotspot </span> </a></li> <li><a href="#"> <span> live broadcast </span> </a></li> <li><a href="#"> <span> picture </span> </a></li> <li><a href="#"> <span> entertainment </span> </a></li> <li><a href="#"> <span> game </span> </a></li> <li><a href="#"> <span> Sports </span> </a></li> </ul> </div> <div> <ul> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality11" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality22" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality33" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality44" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality55" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality66" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality77" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality88" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality99" <hr> </a> </div> </li> <li> <div> <a href="#"> Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality1010" <hr> </a> </div> </li> </ul> <div style="text-align: center; height: 80px"> <img src="img/loading2.gif" height="100%"> </div> <div> <div> <div id="light-pagination"></div> </div> </div> <div id="no" style="text-align: center;color: red;font-size: 20px"></div> </div> </div> </body> <script src="js/jquery-3.3.1.min.js"></script> <script> //1. Define send request flag let send = true; //2. Define the current page number and the number of bars displayed per page let start = 1; let pageSize = 10; //3. Define the distance between the scroll bar and the bottom let battom = 1; //4. Set page loading event $(function () { //5. Bind scrollbar scrolling events to the current window $(window).scroll(function () { //6. Obtain necessary information to calculate whether the current display data has been browsed //Height of the current window let windowHeight = $(window).height(); //Scroll bar scroll distance from top to bottom let scrollTop = $(window).scrollTop(); //Height of the current document let docHeight = $(document).height(); //7. Calculate whether the current display data has been browsed //When the distance from the bottom of the scroll bar + the distance from the current scroll bar + the height of the current window > = the height of the current document if((battom + scrollTop + windowHeight) >= docHeight){ //8. Judge whether the request flag is true if(send == true){ //9. Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed. send = false; //10. Request to query paging data according to the current page and the number of entries displayed on each page queryByPage(start,pageSize); //11. Current page + 1 start++; } } }); }); //Define functions to query paging data function queryByPage(start,pageSize){ //Loading dynamic diagram display $(".loading").show(); //Launch AJAX request $.ajax({ //Requested resource path url:"newsServlet", //Requested parameters data:{"start":start,"pageSize":pageSize}, //How to request type:"POST", //Response data form dataType:"json", //Callback function after successful request success:function (data) { if(data.length == 0) { $(".loading").hide(); $("#no").html("I have a bottom line, too..."); return; } //Load dynamic hide $(".loading").hide(); //Display data let titles = ""; for(let i = 0; i < data.length; i++) { titles += "<li>\n" + " <div class=\"title-box\">\n" + " <a href=\"#\" class=\"link\">\n" + data[i].title + " <hr>\n" + " </a>\n" + " </div>\n" + " </li>"; } //Show to page $(".news_list").append(titles); //Set request flag to true send = true; } }); } </script> </html>

Click button page

  • Case effect

Analysis and implementation of cases

  • page
    1. Introduce the style file and js file of the paging plug-in.
    2. Define the current page number and the number of bars displayed per page.
    3. Call the function to query data.
    4. Define the function to query paging data, and initiate AJAX asynchronous request.
    5. Set the page number parameter (total pages and current pages) for the paging button area.
    6. Bind the click event for the paging button to complete the query function of the previous page and the next page.
  • The server
    1. Get the request parameters.
    2. According to the current Page number and the number of items displayed on each Page, call the method of the business layer to get the paging Page object.
    3. Encapsulate the PageInfo object.
    4. Convert the data to json.
    5. Respond the data to the client.

code:
html page:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Homepage</title> <link rel="stylesheet" href="css/tt.css"> <link rel="stylesheet" href="css/simplePagination.css"> </head> <body> <div> <span>download APP</span> <span> Beijing a sunny day</span> <span>More products</span> </div> <div> <div> <a> <img src="img/logo.png"><br/> </a> <ul> <li> <a href="#"> <span> recommend </span> </a> </li> <li><a href="#"> <span> video </span> </a></li> <li><a href="#"> <span> hotspot </span> </a></li> <li><a href="#"> <span> live broadcast </span> </a></li> <li><a href="#"> <span> picture </span> </a></li> <li><a href="#"> <span> entertainment </span> </a></li> <li><a href="#"> <span> game </span> </a></li> <li><a href="#"> <span> Sports </span> </a></li> </ul> </div> <div> <ul> </ul> <div> <div> <div id="light-pagination"></div> </div> </div> </div> </div> </body> <script src="js/jquery-3.3.1.min.js"></script> <script src="js/jquery.simplePagination.js"></script> <script> //1. Define the current page number and the number of bars displayed per page let start = 1; let pageSize = 10; //2. Call the method to query data queryByPage(start,pageSize); //3. Define the function to query the paging data, initiate AJAX asynchronous request, and display the data to the page function queryByPage(start,pageSize) { $.ajax({ //Requested resource path url:"newsServlet2", //Requested parameters data:{"start":start,"pageSize":pageSize}, //How to request type:"post", //Response data form dataType:"json", //Callback function after successful request success:function (pageInfo) { //Show data to page let titles = ""; for(let i = 0; i < pageInfo.list.length; i++) { titles += "<li>\n" + " <div class=\"title-box\">\n" + " <a href=\"#\" class=\"link\">\n" + pageInfo.list[i].title + " <hr>\n" + " </a>\n" + " </div>\n" + " </li>"; } $(".news_list").html(titles); //4. Set page number parameters (total pages and current pages) for page button area $("#light-pagination").pagination({ pages:pageInfo.pages, currentPage:pageInfo.pageNum }); //5. Bind the click event for the paging button to complete the query function of the previous page and the next page $("#light-pagination .page-link").click(function () { //Get the text content of the click button let page = $(this).html(); //If Prev is clicked, call the query method to query the data on the previous page of the current page if(page == "Prev") { queryByPage(pageInfo.pageNum - 1,pageSize); }else if (page == "Next") { //If you click Next, call the query method to query the data on the Next page of the current page queryByPage(pageInfo.pageNum + 1,pageSize); } else { //Call the query method to query the data of the current page queryByPage(page,pageSize); } }); } }); } </script> </html>

Control layer:

package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.pagehelper.Page; import com.github.pagehelper.PageInfo; import com.itheima.bean.News; import com.itheima.service.NewsService; import com.itheima.service.impl.NewsServiceImpl; 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.util.List; @WebServlet("/newsServlet2") public class NewsServlet2 extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Set the encoding of requests and responses req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); //1. Get request parameters String start = req.getParameter("start"); String pageSize = req.getParameter("pageSize"); //2. Call the query method of the business layer according to the current Page number and the number of items displayed on each Page to get the paged Page object NewsService service = new NewsServiceImpl(); Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize)); //3. Encapsulate PageInfo object PageInfo<List<News>> info = new PageInfo<>(page); //4. Convert the data to JSON String json = new ObjectMapper().writeValueAsString(info); //5. Respond the data to the client resp.getWriter().write(json); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }

Business layer:

package com.itheima.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.mapper.NewsMapper; import com.itheima.service.NewsService; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class NewsServiceImpl implements NewsService { @Override public Page pageQuery(Integer start, Integer pageSize) { InputStream is = null; SqlSession sqlSession = null; Page page = null; try{ //1. Load core configuration file is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2. Get SqlSession factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3. Get SqlSession object through SqlSession factory object sqlSession = sqlSessionFactory.openSession(true); //4. Get the implementation class object of NewsMapper interface NewsMapper mapper = sqlSession.getMapper(NewsMapper.class); //5. Package Page object start: current Page pageSize: number of pieces displayed per Page page = PageHelper.startPage(start,pageSize); //6. Call all the query methods to implement class objects. At this time, the bottom layer executes MySQL limit paging query statement mapper.selectAll(); } catch (Exception e) { e.printStackTrace(); } finally { //7. Release resources if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //8. Return the page object to the control layer return page; } }

DAO layer:

package com.itheima.mapper; import com.itheima.bean.News; import org.apache.ibatis.annotations.Select; import java.util.List; public interface NewsMapper { /* Query all */ @Select("SELECT * FROM news") public abstract List<News> selectAll(); }

27 June 2020, 22:50 | Views: 2063

Add new comment

For adding a comment, please log in
or create account

0 comments