Implement dataTable plug-in in SSM to realize paging

Keywords: SQL xml JQuery JSON

01 download resource file

The following three JS and CSS resource files are introduced into the project in the BootStrap front-end framework
<!-- DataTables -->
<script src="/static/assets/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/static/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<!-- DataTables -->
<link rel="stylesheet" href="/static/assets/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">

02 initialization of front-end start dataTable plug-in

Establish
<script>
$(function(){
     $("#dataTable").dataTable({
         "paging": true,  //Enable local paging or not
         "info": true,  //Controls whether information in the lower left corner of the table is displayed
         "lengthChange":false,  //Allow users to change the number of records displayed on each page of the form
         "ordering":false,  //Allow Datatables to enable sorting
         "processing":true,  //Whether to display the processing status (this will also be displayed if the data takes a long time to sort)
         "searching":false, //Allow Datatables to enable local search
         "serverSide":true,  //Whether to turn on server mode
          "deferRender":true,  //Controlling the delay rendering of Datatables can improve the speed of initialization
         "ajax":{   //Add or modify the request data submitted to the server through Ajax
             "url":"/user/page"  //url to request background data
         },
         "columns":[    //After getting the background JSON package, set the data in the parameter data to display in the table
             {"data":"id"},
             {"data":"username"},
             {"data":"phone"},
             {"data":"email"},
             {"data":"updated"},
             {
                 "data": function (row,type,val,meta) {
                     return '<a href="#"Type =" button "class =" BTN BTN default BTN SM ">+
                            '<a href="#"Type =" button "class =" BTN BTN primary BTN SM ">+
                            '<a href="#"Type =" button "class =" BTN BTN danger BTN SM "> < I class =" Fa FA trash o "> < I > delete < / a > & nbsp; & nbsp;"
                 }
             }
             ],
    "language": { //Internationalization (English to Chinese)
        "sProcessing": "In processing...",
        "sLengthMenu": "display _MENU_ Item result",
        "sZeroRecords": "No match",
        "sInfo": "Display section _START_ to _END_ Results of _TOTAL_ term",
        "sInfoEmpty": "Show results 0 to 0 of 0",
        "sInfoFiltered": "(from _MAX_ Item result filter)",
        "sInfoPostFix": "",
        "sSearch": "search:",
        "sUrl": "",
        "sEmptyTable": "Data in the table is empty",
        "sLoadingRecords": "Loading...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "home page",
            "sPrevious": "page-up key",
            "sNext": "next page",
            "sLast": "Last"
        },
        "oAria": {
            "sSortAscending": ": Sort this column in ascending order",
            "sSortDescending": ": Sort this column in descending order"
        }
    }
     });
 });
</script>

03 back end related codes

Spring MVC controller layer creates corresponding interfaces
@Controller
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private TbUserService tbUserService;

  /**
    *Paging query
     *@param request
     *@Return
     *
     */
    @ResponseBody
    @RequestMapping(value="page",method = RequestMethod.GET)
    public Map<String,Object> page(HttpServletRequest request){
        Map<String,Object> result =new HashMap<>();
        //dataTable will pass the following three parameters to the backend
        String strDraw =request.getParameter("draw");    //Draw the counter. This is used to ensure that Ajax returns from the server are corresponding (AJAX is asynchronous, so the order of returns is uncertain). Request to return after the server receives this parameter
        String strStart =request.getParameter("start");  //The starting position of the first data, for example, 0 represents the first data
        String strLength =request.getParameter("length");   //Total number of pieces needed
        int draw = strDraw == null ? 0 : Integer.parseInt(strDraw);
        int start = strStart == null ? 0 : Integer.parseInt(strStart);
        int length = strLength == null ? 10 : Integer.parseInt(strLength);

        List<TbUser> tbUsers = tbUserService.page(start, length);
        for(TbUser tbUser :tbUsers){
            System.out.println(tbUser.getUsername());
        }
        int count =tbUserService.count(); //count is the total number of data entries in this table. You need to write a related dao layer interface to implement the query.
        result.put("draw", draw);
        result.put("recordsTotal", count);
        result.put("recordsFiltered", count);
        result.put("data", tbUsers);
        result.put("error", "");
        return result;
    }
The service layer creates corresponding interfaces and implementation classes
//Service layer interface class
public interface TbUserService {
/**
     *Paging query
     *@param start Record where to start
     *@param length Records per page
     *@return
     *
     */
    List<TbUser> page(int start , int length);
}
//Service layer interface implementation class
@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    private TbUserDao tbUserDao;
    
    @Override
    public List<TbUser> page(int start, int length) {
    Map<String,Object> params=new HashMap<>();
    params.put("start",start);
    params.put("length",length);
    return tbUserDao.page(params);
    }

Dao layer creates corresponding interface and writes sql statement of mapper.xml of mybatis
//Dao interface
@Repository
public interface TbUserDao {

/**
     *Paging query
     *@param params Two parameters are required, start / record start position length / records per page
     *@Return
     *
     */
    List<TbUser> page(Map<String,Object> params);
    }

//Realizing sql with Mapper.xml corresponding to Dao
 <!--Paging query-->
<select id="page" resultType="TbUser" parameterType="java.util.Map">
    SELECT
    <include refid="tbUserColumns" />
    FROM
    tb_user AS a LIMIT #{start}, #{length}
</select>

04 front end related codes

  <table id="dataTable">
    <thead>
        <tr>
        <th>ID</th>
        <th>User name</th>
        <th>Cell-phone number</th>
        <th>Mail box number</th>
        <th>Update time</th>
         <th>operation</th>
        </tr>
    </thead>
    <tbody>
     
    </tbody>
    </table>
Published 7 original articles, won praise 1, visited 220
Private letter follow

Posted by DaZZleD on Thu, 30 Jan 2020 06:43:38 -0800