search
HomeWeb Front-endJS TutorialBootstrapTable usage backend uses SpringMVC+Hibernate

This article is mainly about letting you play with BootstrapTable easily. The backend uses SpringMVC+Hibernate, which has a certain reference value. Interested friends can refer to it

It’s still the old saying, it’s not as easy to remember as it is Bad writing. I remember that there was pagination in a previous Demo project, but no plug-in was used. I hand-written the paging process, but the effect was not very good. Recently I came into contact with the plug-in BootstrapTable, which has the same style as Bootstrap. Now let’s talk about how to use it.

When you first get started, you can directly insert json data into it, and then set the paging method to client'. The table will be created quickly. However, in general projects, the background is used for paging, and it is impossible to start paging at once. Thousands of pieces of data were retrieved from the database. Not to mention the traffic problem, the client-side rendering was also difficult. In the process of using server back-end paging, I also encountered some problems. I believe that most people who come into contact with BootstrapTable for the first time will encounter them. So hereby write a complete example, which should be continued to be improved later, including additions, deletions, and changes.

Okay, stop talking nonsense and get on with the code.

Let’s start with the project structure:

The project is built using maven. Since the project structure is not very complicated, I won’t introduce it too much.
Next look at index.jsp


<%@ page contentType="text/html;charset=UTF-8"%> 
<html> 
 
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" /> 
<link rel="stylesheet" href="css/bootstrap-table.css" type="text/css"> 
<script type="text/javascript" src="js/jquery-2.0.0.min.js"></script> 
<script type="text/javascript" src="js/bootstrap.js"></script> 
<script type="text/javascript" src="js/bootstrap-table.js"></script> 
<script type="text/javascript" src="js/bootstrap-table-zh-CN.js"></script> 
 
<body> 
  <p class="panel panel-default"> 
    <p class="panel-heading"> 
      <h3 id="Bootstrap-table样例演示">Bootstrap-table样例演示</h3> 
    </p> 
    <p class="panel-body"> 
 
      <p id="toolbar" class="btn-group"> 
      <button id="btn_edit" type="button" class="btn btn-default"> 
        <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改 
      </button> 
      <button id="btn_delete" type="button" class="btn btn-default"> 
        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除 
      </button> 
    </p> 
 
    <table data-toggle="table" id="table" data-height="400" 
      data-classes="table table-hover" data-striped="true" 
      data-pagination="true" data-side-pagination="server" 
      data-search="true" data-show-refresh="true" data-show-toggle="true" 
      data-show-columns="true" data-toolbar="#toolbar"> 
      <thead> 
        <tr> 
          <th data-field="state" data-checkbox=&#39;ture&#39;></th> 
          <th></th> 
          <th></th> 
          <th></th> 
          <th></th> 
        </tr> 
      </thead> 
    </table> 
  </p> 
  </p> 
 
 
</body> 
 
<script type="text/javascript"> 
  $("#superBtn").click(function() { 
    $.get("getPageInfo?limit=5&offset=0", function(data, status) { 
      alert(status); 
      alert(data.userList[0].name); 
    }); 
  }); 
   
  $(document).ready(function(){ 
    $("button[name=&#39;toggle&#39;]").height(20); 
    $("button[name=&#39;refresh&#39;]").height(20); 
  }); 
 
  function edit(id) { 
    alert(id); 
  } 
 
  $("#table") 
      .bootstrapTable( 
          { 
            url : "getPageInfo",  //数据请求路径 
            clickToSelect : true, //点击表格项即可选择 
            dataType : "json",  //后端数据传递类型 
            pageSize : 5, 
            pageList : [ 5, 10, 20 ], 
          // contentType : "application/x-www-form-urlencoded", 
            method : &#39;get&#39;,   //请求类型 
            dataField : "data", //很重要,这是后端返回的实体数据!          
            //是否显示详细视图和列表视图的切换按钮 
            queryParams : function(params) {//自定义参数,这里的参数是传给后台的,我这是是分页用的  
              return {//这里的params是table提供的  
                offset : params.offset,//从数据库第几条记录开始  
                limit : params.limit 
              //找多少条  
              }; 
            }, 
            responseHandler : function(res) { 
              //在ajax获取到数据,渲染表格之前,修改数据源 
              return res; 
            }, 
            columns : [ 
                { 
                  field : &#39;state&#39;, 
                }, 
                { 
                  field : &#39;id&#39;, 
                  title : &#39;ID&#39;, 
                  align : &#39;center&#39; 
                }, 
                { 
                  field : &#39;name&#39;, 
                  title : &#39;姓名&#39;, 
                  align : &#39;center&#39; 
                }, 
                { 
                  field : &#39;age&#39;, 
                  title : &#39;年龄&#39;, 
                  align : &#39;center&#39; 
                }, 
                { 
                  field : &#39;address&#39;, 
                  title : &#39;地址&#39;, 
                  align : &#39;center&#39; 
                }, 
                { 
                  title : &#39;操作&#39;, 
                  field : &#39;id&#39;, 
                  align : &#39;center&#39;, 
                  formatter : function(value, row, index) { 
                    var e = &#39;<a href="#" mce_href="#" onclick="edit(\&#39;&#39; 
                        + row.id + &#39;\&#39;)">编辑</a> &#39;; 
                    var d = &#39;<a href="#" mce_href="#" onclick="del(\&#39;&#39; 
                        + row.id + &#39;\&#39;)">删除</a> &#39;; 
                    return e + d; 
                  } 
 
                } ] 
          }); 
</script> 
</html>

Important points:

1. Import the necessary css files and js files, And pay attention to the version issue, which will be discussed later.

2. queryParams: This is the data passed from the front end to the back end when clicking paging or loading the table for the first time. There are two data, namely limit and offset. Limit means The number of records requested, offset represents the offset of the record

3. dataField: represents the object data passed by the backend, and the name must be the same as the name of the object.

Let’s look at the Controller again:


package controller; 
 
import java.util.Map; 
 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import dao.UserDao; 
 
@Controller 
public class BootstrapTableController { 
 
  @RequestMapping("/getPageInfo") 
  public @ResponseBody Map<String,Object> getPageInfo(int limit,int offset) { 
    System.out.println("limit is:"+limit); 
    System.out.println("offset is:"+offset); 
    UserDao userDao = new UserDao(); 
    Map<String,Object> map = userDao.queryPageInfo(limit, offset); 
    return map; 
  } 
}

The Controller receives the limit and offset parameters passed from the front end, and then calls based on these two parameters. layer method to obtain data. Look at UserDao again:


package dao; 
 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.query.Query; 
 
import entity.User; 
 
public class UserDao { 
 
  private Session session; 
 
  private Transaction transaction; 
 
  public Session getSession() { 
    Configuration config = new Configuration().configure(); 
    SessionFactory sessionFactory = config.buildSessionFactory(); 
    Session session = sessionFactory.openSession(); 
    return session; 
  } 
 
  public Map<String, Object> queryPageInfo(int limit, int offset) { 
    String sql = "from User"; 
    Session session = this.getSession(); 
 
    Query query = session.createQuery(sql); 
    query.setFirstResult(offset); 
    query.setMaxResults(limit); 
    List<User> userList = query.list(); 
 
    String sql2 = "select count(*) from User"; 
    int totalRecord = Integer.parseInt(session.createQuery(sql2).uniqueResult().toString()); 
 
    Map<String, Object> map = new HashMap<String, Object>(); 
    map.put("total", totalRecord); 
    map.put("data", userList); 
    return map; 
  } 
}

userDao is also relatively simple. The key is total and data. This is the data to be returned to the front desk. Note that the name must be the same as the front desk Correspondingly, you only need to return the entity data and total number of records, and BootstrapTable will do the rest for you.
Next, let’s take a look at the User in the entity layer


package entity; 
 
public class User { 
 
  private int id; 
   
  private String name; 
   
  private int age; 
   
  private String address; 
 
  public User() { 
    super(); 
  } 
 
  public User(int id,String name, int age, String address) { 
    super(); 
    this.id = id; 
    this.name = name; 
    this.age = age; 
    this.address = address; 
  } 
 
  public String getName() { 
    return name; 
  }   
 
  public int getId() { 
    return id; 
  } 
 
  public void setId(int id) { 
    this.id = id; 
  } 
 
  public void setName(String name) { 
    this.name = name; 
  } 
 
  public int getAge() { 
    return age; 
  } 
 
  public void setAge(int age) { 
    this.age = age; 
  } 
 
  public String getAddress() { 
    return address; 
  } 
 
  public void setAddress(String address) { 
    this.address = address; 
  } 
 
  @Override 
  public String toString() { 
    return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; 
  } 
}

There are also several configuration files, namely the SpirngMVC configuration file and web.xml And pom.xml, what should be matched should be matched:

SpringMVC-servlet.xml:


##

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" 
xsi:schemaLocation=" 
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
 http://www.springframework.org/schema/util 
 http://www.springframework.org/schema/util/spring-util-4.3.xsd 
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-4.3.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> 
 
<!--   <mvc:annotation-driven/>  --> 
  <mvc:annotation-driven> 
    <mvc:message-converters> 
      <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> 
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> 
    </mvc:message-converters> 
  </mvc:annotation-driven> 
 
  <context:component-scan base-package="controller"/> 
  
  <!-- 这两个类用来启动基于Spring MVC的注解功能,将控制器与方法映射加入到容器中 --> 
  <bean 
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 
  <bean 
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
 
  <!-- 这个类用于Spring MVC视图解析 --> 
  <bean id="viewResolver" 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix" value="/WEB-INF/pages/" /> 
    <property name="suffix" value=".jsp" /> 
  </bean> 
  
</beans>

web.xml:



<!DOCTYPE web-app PUBLIC 
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
 "http://java.sun.com/dtd/web-app_2_3.dtd" > 
 
<web-app> 
  <display-name>Archetype Created Web Application</display-name> 
 
  <servlet> 
    <servlet-name>SpringMVC</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
  </servlet> 
  <servlet-mapping> 
    <servlet-name>SpringMVC</servlet-name> 
    <url-pattern>/</url-pattern> 
  </servlet-mapping> 
 
  <servlet-mapping> 
    <servlet-name>default</servlet-name> 
    <url-pattern>*.css</url-pattern> 
  </servlet-mapping> 
  <servlet-mapping> 
    <servlet-name>default</servlet-name> 
    <url-pattern>*.js</url-pattern> 
  </servlet-mapping> 
  <servlet-mapping> 
    <servlet-name>default</servlet-name> 
    <url-pattern>*.ttf</url-pattern> 
  </servlet-mapping> 
  <servlet-mapping> 
    <servlet-name>default</servlet-name> 
    <url-pattern>*.woff</url-pattern> 
  </servlet-mapping> 
  <servlet-mapping> 
    <servlet-name>default</servlet-name> 
    <url-pattern>*.woff2</url-pattern> 
  </servlet-mapping> 
 
</web-app>

pom.xml:



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 
  <modelVersion>4.0.0</modelVersion> 
  <groupId>Demo</groupId> 
  <artifactId>BootstrapDemo</artifactId> 
  <packaging>war</packaging> 
  <version>0.0.1-SNAPSHOT</version> 
  <name>BootstrapDemo Maven Webapp</name> 
  <url>http://maven.apache.org</url> 
  <dependencies> 
    <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>3.8.1</version> 
      <scope>test</scope> 
    </dependency> 
    <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>javax.servlet-api</artifactId> 
      <version>3.1.0</version> 
      <scope>provided</scope> 
    </dependency> 
    <dependency> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-core</artifactId> 
      <version>5.2.6.Final</version> 
    </dependency> 
 
    <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
      <version>5.1.41</version> 
    </dependency> 
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-webmvc</artifactId> 
      <version>4.3.10.RELEASE</version> 
    </dependency> 
    <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-core</artifactId> 
      <version>2.8.9</version> 
    </dependency> 
    <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-databind</artifactId> 
      <version>2.8.9</version> 
    </dependency> 
      <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-annotations</artifactId> 
      <version>2.8.9</version> 
    </dependency> 
  </dependencies> 
  <build> 
    <finalName>BootstrapDemo</finalName> 
  </build> 
</project>

Then forget about the dao layer, it’s very Simple. Basically all the keys have been displayed here. Let’s take a look at the effect:

I don’t know if you have noticed that the button in the upper right corner is obviously larger. Circle, this is not good. In fact, the two buttons on the left are a circle smaller. I have searched online for a long time and basically no one has encountered such a problem. I have no choice but to force me to use a debugger to track these two buttons. button element, and finally use jQuery to manually change its size after the table is loaded, and then it works normally.

Of course, this only involves checking data, as well as deleting, adding and modifying data. We will introduce the implementation of these later. In fact, the most critical thing is checking. Once the check is done, the rest will fall into place. .

The above is the detailed content of BootstrapTable usage backend uses SpringMVC+Hibernate. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment