AJAX & search Association & two ways of paging

Posted by rogair on Sun, 28 Jun 2020 07:53:03 +0200

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.
  • What is synchronization
  • What is asynchronous

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.
<!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>

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.
<!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();
        $.get(
          "userServlet",
          "username="+  username,
            function (data) {
                $("#uSpan").html(data);
            },
            "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
<!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({name:value,name:value ,… };
    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.
<!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:"userServletxxx",
            //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, without reloading the whole page, the part of the web page
    Local update by content.
  • 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. It is easy for people to read and write, but also easy for computers to parse and generate, and effective
    Improve network transmission efficiency.
  • Create format
  • common method

JSON conversion tool

  • In addition to using JSON in JavaScript, we can also use JSON in JAVA. The conversion tools of JSON are some JAR toolkits packaged 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. By default, Jackson is used for spring MVC conversion.
  1. Import the jar package.
  2. Create the core object.
  3. Call method to complete the conversion.
  • Common classes
  • Common methods of ObjectMapper
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{name = 'Zhang San', age=23}
     */
    @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 = {name = Zhang San, gender = male}
     */
    @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 1 = User{name = 'Zhang San', age=23}, black horse class 2 = User{name = 'Li Si', age=24}}}
     */
    @Test
    public void test03() throws Exception {
        //Map < string, user > to json
        HashMap<String, User> map = new HashMap<>();
        map.put("Black horse class one", new User("Zhang San", 23));
        map.put("Black horse 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>>() {
        });
        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{name = 'Zhang San', age=23}, User{name = 'Li Si', age=24}]
     */



        @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>>(){});
        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 analysis and Implementation

  • page
  1. Bind the mouse click event to the user name input box.
  2. Get the entered user name data.
  3. Determine whether the user name is empty.
  4. If it is empty, the association prompt box will be hidden.
  5. If it is not empty, the AJAX request is sent and the data of the response is displayed in the association box.
<!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 class="content">
        <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" class="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 entered user name
         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 AJAX request. And display the data to the Lenovo box
         $.ajax({
             //Requested resource path
             url:"userServlet",
             //Request parameters
             data:{"username":username},
             //Request method
             type:"POST",
             //Response data form
             dataType:"json",
             //Callback function after successful request
             success:function (data) {
                 //Display the returned data to show's div
                 let names = "";
                 for(let i = 0; i < data.length; i++) {
                     names += "<div>"+data[i].name+"</div>";
                 }
                 $("#show").html(names);
                 $("#show").show();
             }
         });
     });
</script>
</html>
  • Control layer
  1. Get the request parameters.
  2. Call the fuzzy query method of the business layer.
  3. Turn the returned data into JSON and respond to the client.
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);
    }
}

Comprehensive case paging

Waterfall flow infinite load data paging

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 tag.
  2. Defines the current page number and the number of bars displayed per page.
  3. Defines the distance from the bottom of the scroll bar.
  4. Set the page load event.
  5. Binds a scroll bar scroll event to the current window.
  6. Get the necessary information (height of the current window, the distance of scrolling up and down the scroll bar, height of the current document).
  7. Calculate whether the current display data has been browsed.
  8. Determine whether the request flag is true.
  9. Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed.
  10. Query paging data based on the current page and the number of entries displayed per page.
  11. Current page number + 1.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Homepage</title>
    <link rel="stylesheet" href="css/tt.css">
</head>
<body>
<div class="top">
    <span class="top-left">downloadAPP</span>
    <span class="top-left"> Beijing         a sunny day</span>
    <span class="top-right">More products</span>
</div>

<div class="container">

    <div class="left">
        <a>
            <img src="img/logo.png"><br/>
        </a>

        <ul>
            <li>
                <a class="channel-item active" href="#">
                    <span>
                        recommend
                    </span>
                </a>
            </li>

            <li><a class="channel-item" href="#">
                <span>
                    video
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    hotspot
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    live broadcast
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    picture
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    entertainment
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    game
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    Sports
                </span>
            </a></li>

        </ul>

    </div>
    <div class="center">
        <ul class="news_list">
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality11"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality22"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality33"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality44"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality55"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality66"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality77"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality88"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality99"
                        <hr>
                    </a>
                </div>
            </li>
            <li>
                <div class="title-box">
                    <a href="#" class="link">
                        Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality1010"
                        <hr>
                    </a>
                </div>
            </li>
        </ul>

        <div class="loading" style="text-align: center; height: 80px">
            <img src="img/loading2.gif" height="100%">
        </div>

        <div class="content">
            <div class="pagination-holder clearfix">
                <div id="light-pagination" class="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 bottom = 50;

      //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((bottom + 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>
  • 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. Turn the resulting data into json.
  4. Respond the data to the client.
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");

        //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. Convert the data to JSON
        String json = new ObjectMapper().writeValueAsString(page);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //4. Respond the data to the client
        resp.getWriter().write(json);
    }

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

Click button page

Analysis and implementation of cases

  • page
  1. The style file and js file of the paging plug-in are introduced.
  2. Defines the current page number and the number of bars displayed per page.
  3. Call the function that queries the data.
  4. Define the function to query paging data, and initiate AJAX asynchronous request.
  5. Set page number parameters (total and current pages) for the page button area.
  6. Bind the click event for the paging button to complete the query function of the previous page and the next 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 class="top">
    <span class="top-left">downloadAPP</span>
    <span class="top-left"> Beijing         a sunny day</span>
    <span class="top-right">More products</span>
</div>

<div class="container">

    <div class="left">
        <a>
            <img src="img/logo.png"><br/>
        </a>

        <ul>
            <li>
                <a class="channel-item active" href="#">
                    <span>
                        recommend
                    </span>
                </a>
            </li>

            <li><a class="channel-item" href="#">
                <span>
                    video
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    hotspot
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    live broadcast
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    picture
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    entertainment
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    game
                </span>
            </a></li>

            <li><a class="channel-item" href="#">
                <span>
                    Sports
                </span>
            </a></li>
        </ul>

    </div>
    <div class="center">
        <ul class="news_list">

        </ul>

        <div class="content">
            <div class="pagination-holder clearfix">
                <div id="light-pagination" class="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>
  • 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. Encapsulates the PageInfo object.
  4. Turn the resulting data into json.
  5. Respond the data to the client.
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);
    }
}

Topics: JSON Java JQuery xml