JavaEE three-layer architecture implements ajax pagination query
Development environment:
Step 1: Preparation of code implementation
There are many posts on the Internet when developing preliminary configuration work in IDEA, so I will not repeat it here. I mainly talk about three points.
In the server configuration, you need to select update classes and resource for the two items in the red box. After selecting, you can achieve hot deployment.
To fill in the name of the project here. As the root path of the project
The way to import the jar package is shown in the figure. Click the plus sign in dependence and select the lib folder you created.
Import related jar packages: c3p0 jar package, DbUtils tool class jar package, fastJson jar package, mysql driver jar package
Write the following data in the product table of database test03
Subcontracting the project in IDEA and importing the c3p0 connection pool configuration
Note that the c3p0 configuration file should be modified to its own database name and database password
In the domain package, create the Product entity class, write the corresponding properties in the Product class based on the fields of the product table in the database. Generate the get set method.
Create a tool class to get connection pool objects
Step 2: Query all product information without paging
Implementation ideas:
jsp/html----->servlet(web layer handles request and response data) ----------------->service(service layer processing logic)------------------->dao(dao layer handles database operations)
Create a product page and send a request to the server (get all product information)
The front-end uses bootstrap responsive development, which can make the page more beautiful and the development is more convenient.
The code for the page information is as follows:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Product Display List</title> <!--Introduce bootstrap-related files--> <link rel="stylesheet" href="/ajax_product/bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" > <script type="text/javascript" src="/ajax_product/bootstrap/js/jquery-1.11.3.js"></script> <script type="text/javascript" src="/ajax_product/bootstrap/js/bootstrap.js"></script></head><script type="text/javascript"> //When the page is loading, a request is sent to the server to receive all product data $(function () { //=========================================================================================================================================================================================================================================================================================================================================================================================================================================== //Analyze all data transmitted from the server//======================================================= Show product information to the table var products = eval(data); //Tranquility data for (var i = 0; i < products.length; i++) { //Tranquility of data var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"</td><td>"+products[i].count+"</td><td>"+products[i].price+"</td></tr>"); // and add to the table, add data to the table $("#tab").append(protd); } },"json") })</script><body><h3 align="center">Promotional product display</h3><div> <!--The product table occupies one row--> <div> <div> <!--table-hover means that when the mouse moves into this row table, the color change table-bordered means that the table is bordered --> <table id="tab"> <tr> <th>Number</th> <th>Product name</th> <th>Quantity</th> <th>Product quantity</th> <th>Product unit price</th> </tr> </table> </div> </div></div></body></html>Create a servlet to receive requests and get all product information
In IDEA, create a servlet as shown in the following figure
Automatically generate annotations without checking here
After clicking OK, IDEA will automatically jump to the web.xml file, and automatically write the full path name of the Servlet, just write the url-pattern.
Note that the url-pattern needs to be written consistent with the servlet in the ajax request.
The code of the web layer Servlet is as follows:
package com.thc.web;import com.alibaba.fastjson.JSONObject;import com.thc.service.ProductService;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.sql.SQLException;import java.util.List;public class Product extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle garbled code request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //Because it displays all product information, there is no parameter to receive //The service layer needs to call the method to find all data, get the result, and respond to the client ProductService service = new ProductService(); try { //Call the methods of the business layer to get all the products List<com.thc.domain.Product> allProuct = service.findAllProuct(); //Convert the obtained data into json type data String jsonString = JSONObject.toJSONString(allProuct); //Write back to the browser response.getWriter().write(jsonString); } catch (SQLException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}In the service layer, obtain data from the dao layer and return it to the Servlet in the web layer
The code for calling the service layer in the web layer is as follows
package com.thc.service;import com.thc.dao.ProductDao;import com.thc.domain.Product;import java.sql.SQLException;import java.util.List;public class ProductService { //In the service layer, obtain data from the dao layer and return data to the web layer public List<Product> findAllProuct() throws SQLException { ProductDao dao = new ProductDao(); //Calling the dao layer to query all products List<Product> allProduct = dao.findAllProduct(); return allProduct; }}Query data from the server in the dao layer and give the service layer
package com.thc.dao;import com.thc.domain.Product;import com.thc.utils.JdbcUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.SQLException;import java.util.List;//====================================== The dao layer is specifically responsible for database operations public class ProductDao { //============= Query all product information public List<Product> findAllProduct() throws SQLException { //Use dbutils to create the QueryRunner core object QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); //Write the sql statement to query all products String sql = "select * from product"; //Convert the product to the product into a list collection, and the generic to product List<Product> products = qr.query(sql, new BeanListHandler<>(Product.class)); return products; }}After the dao layer gets the data, it passes it to the service layer. The service layer then passes it to the servlet of the web layer. After the servlet gets the data, it is saved in the list collection, and then converts the list collection into a json data type and writes it to the browser. The following code in the front-end page is to parse the json data returned by the servlet
$.post(url,function (data) { //Analyze all data transmitted from the server//==================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================== and add to the table, add data to the table $("#tab").append(protd); } },"json")Through the package grabber tool provided by Google Chrome, you can see the data of the servlet response
Copy all the response data, which is the following data. An array has the product object nested.
Objects all exist in the form of key-value pairs.
For example, in the first data, the key is count and the value is 100. The key is id, the value is 1, the key is name, the value is TV, the key is price, the value is 2000
[ {"count":100,"id":1,"name":"TV","price":2000}, {"count":200,"id":2,"name":"washing machine","price":1000}, {"count":300,"id":3,"name":"air conditioner","price":3000}, {"count":50,"id":4,"name":"Projector","price":2000}, {"count":1000,"id":5,"name":"HP computer","price":4000}, {"count":100,"id":6,"name":"Apple phone","price":5000}, {"count":60,"id":7,"name":"sewing machine","price":2000}, {"count":100,"id":8,"name":"Xiaomi Box","price":2200}, {"count":300,"id":9,"name":"Dispenser","price":2000}, {"count":200,"id":10,"name":"Water purifier","price":2000}, {"count":500,"id":11,"name":"Electric Heater","price":2000}, {"count":100,"id":12,"name":"Juicker","price":399}, {"count":200,"id":13,"name":"Electric pressure cooker","price":498}, {"count":300,"id":14,"name":"Rice cooker","price":299}, {"count":50,"id":15,"name":"Microwave oven","price":1299}, {"count":200,"id":16,"name":"Soy milk maker","price":199}, {"count":300,"id":17,"name":"Induction cooker","price":398}, {"count":500,"id":18,"name":"humidifier","price":99}, {"count":250,"id":19,"name":"Razor","price":98}, {"count":1000,"id":20,"name":"Safety","price":16.5}, {"count":1200,"id":21,"name":"Diapai","price":8.8}, {"count":1500,"id":22,"name":"Libai","price":9.9}]Without pagination, the display effect is as follows:
All the data is displayed in a page. If there is a lot of data, for example, searching for a keyword on Baidu, there may be tens of thousands or hundreds of millions of them. It takes a long time to get so many results from the database and give the browser so much. The user experience is extremely poor, so paging technology is required. Physical paging is used.
Only query the information required for the current page from the database at a time.
Step 3: Pass the current number of pages and the number of pages displayed to the server
The html page needs to increase the current number of pages and the number of displayed pages per page, and pass it to the server
Change the code as shown in the following figure:
In the servlet layer, parameters need to be received and the corresponding data of the current page is queried from the service layer. The code is as follows:
public class Product extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle garbled code request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //The current page int pageNo = Integer.parseInt(request.getParameter("pageNo")); //The number of displayed entries per page int pageSize = Integer.parseInt(request.getParameter("pageSize")); //Because it displays all product information, there is no parameter to receive//The service layer needs to call the method to find all data, get the result, and respond to the client ProductService service = new ProductService(); try { //According to the number of displayed pages and each page, obtain data from the service layer List<com.thc.domain.Product> product = service.findProduct(pageNo, pageSize); String jsonString = JSONObject.toJSONString(product); //Write back to the browser response.getWriter().write(jsonString); } catch (SQLException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}New method of finding current page data added in the service layer
public List<Product> findProduct(int pageNo, int pageSize) throws SQLException { ProductDao dao = new ProductDao(); List<Product> product = dao.findProduct(pageNo, pageSize); return product; }The new method of finding the current page from the database added in the dao layer
public List<Product> findProduct(int pageNo, int pageSize) throws SQLException { QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); String sql ="select * from product limit ?,?"; //limit The first parameter: start from where in the database, the index starts from 0 //The second parameter: how many checks each time //The rule of the first parameter is: subtract the current number of pages by one, multiply by the number of queries per page List<Product> productList = qr.query(sql, new BeanListHandler<>(Product.class), (pageNo - 1) * pageSize, pageSize); return productList; }The browser side displays as shown in the figure below: only product information with pageSize (the current value is 6) will be displayed at a time.
However, it is not possible to dynamically turn pages by clicking the page button.
Then we need to consider how the page displays the paging bar and how the data should be encapsulated?
We know that the number of pages displayed in the page paging bar is dynamically changed . The total number of pages = the total number of data/data displayed on each page should be rounded upwards. In other words, in addition to the List<Product> data, our page also needs the total number of data, the total number of pages, the current page, and the number of displays per page. In addition, the pageNo on the current page also changes dynamically. How many pages are clicked on on the page? PageNo is the number of pageNo. Therefore, we need to create another javabean (PageBean.java) to encapsulate this data, and then convert it into json data and send it to the client to display it.
Step 4: Encapsulate the relevant data of the page into a JavaBean
Create a class named PageBean in the domain package, with the following properties:
private int pageNo;//current page number private int pageSize;//The number of displayed on each page private int totalCount;//How many product information data are there in total private int totalPage;//How many pages of data are there in total private List<Product> products;//Set of product information data
Pass the current number of pages (pageNo) in the service layer and the number of pages displayed on each page (pageSize) and return a PageBean to the web layer.
The final code of the web layer is as follows
public class Product extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle garbled code request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //The current page int pageNo = Integer.parseInt(request.getParameter("pageNo")); //The number of displayed entries per page int pageSize = Integer.parseInt(request.getParameter("pageSize")); //Because it displays all product information, there is no parameter to receive//The service layer needs to call the method to find all data, get the result, and respond to the client ProductService service = new ProductService(); try { /* Call the business layer method to obtain all products List<com.thc.domain.Product> allProuct = service.findAllProuct(); Convert the obtained data into json type data String jsonString = JSONObject.toJSONString(allProuct);*/ //Fetch data from the service layer based on the current page and the number displayed on each page //List<com.thc.domain.Product> product = service.findProduct(pageNo, pageSize); //======================================================================== PageBean pageBean = service.findPageInfo(pageNo, pageSize); //===================================================================================================================================================================================================================================================================== jsonString = JSONObject.toJSONString(pageBean); //======================================================================= response.getWriter().write(jsonString); } catch (SQLException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}In the service, you need to obtain all the information of the pageBean, and pageNo and pageSize are known. You need to obtain the product information data and LIst collection from the dao layer, and you also need to obtain the total product information data totalCount. How many pages can be divided by the total data by the data displayed on each page and rounded upwards.
The final code of the service layer is as follows:
public class ProductService { //In the service layer, obtain data from the dao layer and return the data to the web layer//===================================== public List<Product> findAllProuct() throws SQLException { ProductDao dao = new ProductDao(); //Calling the dao layer to query all products List<Product> allProduct = dao.findAllProduct(); return allProduct; } //========================================================================== public List<Product> findProduct(int pageNo, int pageSize) throws SQLException { ProductDao dao = new ProductDao(); List<Product> product = dao.findProduct(pageNo, pageSize); return product; } //============================================================================ public PageBean findPageInfo(int pageNo, int pageSize) throws SQLException { ProductDao dao = new ProductDao(); List<Product> product = dao.findProduct(pageNo, pageSize); int totalCount = dao.findTotalCount(); PageBean pb = new PageBean(); //Encapsulate data pb.setTotalCount(totalCount); pb.setPageNo(pageNo); pb.setPageSize(pageSize); pb.setProducts(product); //From upwards and calculate the total number of pages. Don't forget to multiply by 1.0, otherwise one page of data will be missing int totalPage = (int) Math.ceil(totalCount*1.0/pageSize); pb.setTotalPage(totalPage); //Give the data to the servlet return pb; }}In the dao layer, a new method is added to query the total number of database information.
The final code of the dao layer is as follows
//============================= The dao layer is specifically responsible for database operations public class ProductDao { //========== Query all product information public List<Product> findAllProduct() throws SQLException { //Use dbutils to create the QueryRunner core object QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); //Write sql statements to query all products String sql = "select * from product"; //Convert the product to the list collection, and the generic to the product is product List<Product> products = qr.query(sql, new BeanListHandler<>(Product.class)); return products; }//================================================= public List<Product> findProduct(int pageNo, int pageSize) throws SQLException { QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); String sql ="select * from product limit ?,?"; //limit The first parameter: where to start in the database, the index starts from 0 //The second parameter: how many each time you check //The rule of the first parameter is: subtract the current number of pages by one, multiply by the number of queries per page List<Product> productList = qr.query(sql, new BeanListHandler<>(Product.class), (pageNo - 1) * pageSize, pageSize); return productList; }//============== How many pieces of data are there in the query? ============================= public int findTotalCount() throws SQLException { QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select count(*) from product"; Long countL =(Long) qr.query(sql, new ScalarHandler()); return countL.intValue(); }}Step 5: Process the front-end page
Under the table tag, add a line to provide the paging component. Comment out the li code because it needs to be displayed dynamically.
Declare the parameter variables to be received first
var url ="/ajax_product/product";var pageNo=1;//The current page is set to 1var pageSize=6;//On each page displays 6 product information var totalPage;//How many pages of data are there in total var products;//Product data information
After writing the post request for ajax, the packet capture tests whether the browser receives data.
$.post( url,//The address of data transmitted to the server {"pageNo": pageNo, "pageSize": pageSize},//The current number of pages and the number of pieces displayed per page function (data) {})I got the following data after catching the packet
{"pageNo":1, "pageSize":6, "products":[{"count":100,"id":1,"name":"TV","price":2000}, {"count":200,"id":2,"name":"washing machine","price":1000}, {"count":300,"id":3,"name":"Air conditioner","price":3000}, {"count":50,"id":4,"name":"Projector","price":2000}, {"count":1000,"id":5,"name":"HP computer","price":4000}, {"count":100,"id":6,"name":"Apple phone","price":5000}], "totalCount":22, "totalPage":3}It means that the server side can respond to the browser normally. Then write the front-end code
Display data in the table
First parse the data obtained by the backend, then synchronize it into the js code, obtain an array of data of all product objects through pagebean.products, then iterate through this array, and splice the value of the product attribute into the table.
The code is as follows
$.post( url,//The address of data transmitted to the server {"pageNo": pageNo, "pageSize": pageSize},//The current number of pages and the number of pieces displayed per page are transmitted to the browser function (data) { //Analyze all pagebean data transmitted from the server, the format is json type var pagebean = eval(data); //Synchronize data pageNo=pagebean.pageNo; pageSize=pagebean.pageSize; totalPage=pagebean.totalPage; products=pagebean.products; //Show data in the table ================================================================================================================================================================================================================================================================================================================================================================ for (var i = 0; i < products.length; i++) { //Transfer data var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+"</td> <td>"+products[i].count+"</td><td>"+products[i].price+"</td> </tr>"); // Add to the table, add data to the table $("#tab").append(protd); } },"json")After writing this code, the server can be turned on to test whether the data can be obtained into the table. The data is successfully displayed after testing.
Display the data of the page bar
First display the data of the previous page and the next page
//Show the data of the page bar//Not considering the function, it can be displayed first//Show the previous page var preLi=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Previous page</a></li>');//Add $(".pager").append(preLi);//Show the next page var nextLi=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Next page</a></li>');//Add $(".pager").append(nextLi);The test results are as follows:
Display page number data:
//Show the data of the page bar//Not considering the function, it can be displayed first//Show the previous page var preLi=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Previous page</a></li>');//Add in $(".pager").append(preLi);//Travel over the page number for (var i = 1; i <= totalPage; i++) { //Create li tag var li=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>'); //Add to ul through the class selector $(".pager").append(li);}//Show the next page var nextLi=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Next page</a></li>');//Add $(".pager").append(nextLi);The effect is shown in the figure below:
The current page is highlighted
Since the pager class does not support highlighting in bootstrap, the pagination class is replaced with pagination.
The logic of highlighting is to determine whether it is the current page (pageNo) when traversing.
Add class's active attribute to the li tag
//Transfer the page number for (var i = 1; i <= totalPage; i++) { var li; if(i===pageNo){ //============== It is the current page, highlight li=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>'); //Add to ul through the class selector $(".pagination").append(li); }else{ //=========== Not the current page, not highlight li=$('<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >'+i+'</a></li>'); //Add to ul through the class selector $(".pagination").append(li); }}The effect is as follows
Add click events to the page number and switch data.
No click event is required on the current page
Add an onclick event to the a tag in the number of pages, and bind a skipPage() function. The operation in the skipPage() function is actually the operation of sending Ajax post request to the server when we get the first page data. Therefore, copy the code of $(function(){}) into the skipPage() function , and then call the skipPage() function when the page loads. Passing 1 means that the page 1 data is loaded by default. At this time, $(function(){}) will only be executed once. skipPage() becomes a recursive function and calls itself. However, a single click event will only call the skipPage method once, which is different from recursion in Java.
After executing this code, click on different codes and find that the content of the table and the page bar will be continuously superimposed.
As shown in the figure below:
Clear the data every time the data is loaded. Clear the page bar
After adding the code to clear the page bar, I found that the page bar has not been superimposed, but the table is still superimposed.
Clear the form
$("#tab").empty(); After executing the clear code for the table, I found the following phenomenon:
The first line of the table is gone, so you need to use a selector to exclude the first line.
$("#tab tr:not(:first)") means
First select the table according to the id selector
Then, from the hierarchical selector, select the tr row
The basic selector first is nested in the basic selector not, which means it is not the first line
The overall meaning is that if the table is not the first row, the empty() method is called to delete all child nodes in the matching element collection.
After testing, the first line of data can be deleted
Determine whether it is available on the previous page, and switch page numbers function
If the current page is the first page, the previous page function is not available.
If the current page is not the first page, add a click event, switch to the previous page, and reduce the page number by one.
//Show the previous page and determine whether var preLi is available; if(pageNo===1){ //If the current page is the first page, the function of the previous page is not available preLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Previous page</a></li>');}else{ preLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skipPage('+(pageNo-1)+')">Previous page</a></li>');}//Use the class selector, add $(".pagination").append(preLi);Determine whether it is available on the next page, and switch page numbers function
If the current page is the last page, the previous page function is not available.
If the current page is not the last page, add a click event, switch to the next page, and add a page number.
//Show the next page and determine whether var nextLi is available; if(pageNo===totalPage){ //If the current page is the last page, the function of the previous page is not available. nextLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external no >Next page</a></li>');}else { //If the current page is not the last page, add a click event, switch to the previous page, and reduce the page number by one. nextLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skipPage('+(pageNo+1)+')">Next page</a></li>');}// Through the class selector, add $(".pagination").append(nextLi);At this point, all the codes on the front-end page are completed and all the functions are implemented.
All the codes of the front-end page are as follows
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Product Display List</title> <!--Introduce bootstrap-related files--> <link rel="stylesheet" href="/ajax_product/bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" > <script type="text/javascript" src="/ajax_product/bootstrap/js/jquery-1.11.3.js"></script> <script type="text/javascript" src="/ajax_product/bootstrap/js/bootstrap.js"></script></head><script type="text/javascript"> var url ="/ajax_product/product"; var pageNo=1;//The current page is set to 1 var pageSize=5;//On each page, 6 product information var totalPage;//How many pages of data are there in total var products;//The product data information//When the page is loaded, a request is sent to the server to receive all product data $(function () { skipPage(1); }); function skipPage(page) { //=============================================================================================================================================================================/Send the post request to the server $.post(url,//The address of data transmission to the server {"pageNo": pageNo, "pageSize": pageSize},//Transfer the current number of pages and the number of pieces displayed per page to the browser function (data) { //Analyze all pagebean data transmitted from the server, the format is json type var pagebean = eval(data); //Synchronous data pageNo=pagebean.pageNo; pageSize=pagebean.pageSize; totalPage=pagebean.totalPage; products=pagebean.products; //Show data in the table======================================================================/$("#tab").empty(); $("#tab tr:not(:first)").empty(); for (var i = 0; i < products.length; i++) { //Tranquility of data in each row var protd =$("<tr><td>"+products[i].id+"</td><td>"+products[i].name+" </td><td>"+products[i].count+"</td><td>"+products[i].price+"</td></tr>"); // Add to the table and add data to the table $("#tab").append(protd); } // Show the data of the page bar ==================================================================/Clear the page bar $(".pagination").empty(); //Don't consider the function first, it can be displayed first //Show the previous page to determine whether var preLi is available; if(pageNo===1){ //If the current page is the first page, the previous page function is not available. preLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Previous page</a> </li>'); }else{ //If the current page is not the first page, add a click event, switch to the previous page, and reduce the page number by one. preLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skipPage('+(pageNo- 1)+')">Previous page</a></li>'); } //Add $(".pagination").append(preLi); //Transfer the page number for (var i = 1; i <= totalPage; i++) { var li; if(i===pageNo){ //============== It is the current page, highlight li=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel=" nofollow" >'+i+'</a> </li>'); //Add to ul through the class selector $(".pagination").append(li); }else{ //========== Not the current page, not highlighted. Add click event, and the parameters are passed as the current page number li=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skipPage('+i+')">'+i+'</a></li>'); //Add to ul through the class selector $(".pagination").append(li); } } //Show the next page and determine whether var nextLi is available; if(pageNo===totalPage){ //If the current page is the last page, the function of the previous page is not available. nextLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Next page</a> </li>'); }else { //If the current page is not the last page, add a click event, switch to the previous page, and reduce the page number by one. nextLi=$('<li><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="skipPage('+ (pageNo+1)+')">Next Page</a></li>'); } //Use the class selector, add $(".pagination").append(nextLi); },"json") }</script><body><h3 align="center">Promotional product display</h3><div> <!--The product table occupies one row--> <div> <div> <!--table-hover means that when the mouse moves into this row of table, the color change table-bordered means that the table is bordered --> <table id="tab"> <tr> <th>number</th> <th>product name</th> <th>quantity</th> <th>product unit price</th> </tr> </table> </div> </div> <div> <div > <nav> <ul> <!--The code here is dynamically generated by js--> </ul> </nav> </div> </div> </div></div></body></html>Summarize
此分页功能,用到了JavaEE的三层架构的思想.每一层各司其职,做各自的负责的事情.前端部分为难点.需要处理的细节很多.前端涉及到了ajax和jquery.jQuery的一些语法与选择器的相关的东西要非常熟练.还用到了bootrap响应式开发,让前端页面的布局更加方便.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.