欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【第二篇】 搞定BootstrapTable(后端使用SpringMVC+Hibernate)

程序员文章站 2022-07-15 10:42:08
...

还是那句老话,好记性不如烂笔头。上次已经将最基本的BootstrapTable的查询做出来了,现在将功能完善一下,添加包括删除用户、添加用户、修改用户信息、按条件查询用户的功能。好了,废话不多说,让我们开始吧!

先看jsp文件:

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.min.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>
	<div class="panel panel-default">
		<div class="panel-heading">
			<h3 class="panel-title text-center">Bootstrap-table样例演示</h3>
		</div>
		<div class="panel-body">

			<div id="toolbar" class="btn-group">
				<button id="btn_save" 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>
				<div class="form-inline">
					<select class="form-control" id="selectForm"  style="margin-left: 20px;">
						<option value="id">ID</option>
						<option value="name">用户名</option>
						<option value="age">年龄</option>
						<option value="address">地址</option>
					</select>
					<input class="form-control" id="searchText" style="margin-top: -70px;margin-left: 250px;" type="text" placeholder="请输入搜索内容"></input>
					<button class="btn btn-info" id="searchBtn" style="margin-top: -70px;">搜索</button>					
				</div>
			</div>

			<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-show-refresh="true" data-show-toggle="true"
				data-show-columns="true" data-toolbar="#toolbar">
				<thead>
					<tr>
						<th data-field="state" data-checkbox='ture'></th>
						<th></th>
						<th></th>
						<th></th>
						<th></th>
					</tr>
				</thead>
			</table>
		</div>
	</div>

	<!-- 编辑用户模态框(Modal) -->
	<div class="modal fade" id="updateModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">×</button>
					<h4 class="modal-title" id="myModalLabel">修改用户信息</h4>
				</div>
				<div class="modal-body">
					<form>
						<div class="form-group">
							<label>姓名</label> <input type="text" class="form-control"
								id="name">
						</div>
						<div class="form-group">
							<label>年龄</label> <input type="number" class="form-control"
								id="age">
						</div>
						<div class="form-group">
							<label>地址</label> <input type="text" class="form-control"
								id="address">
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭
					</button>
					<button type="button" class="btn btn-primary" id="updateConfirmBtn">提交更改</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
	<!-- 添加用户模态框(Modal) -->
	<div class="modal fade" id="saveModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">×</button>
					<h4 class="modal-title" id="myModalLabel">添加用户信息</h4>
				</div>
				<div class="modal-body">
					<form>
						<div class="form-group">
							<label>姓名</label> <input type="text" class="form-control"
								id="saveName">
						</div>
						<div class="form-group">
							<label>年龄</label> <input type="number" class="form-control"
								id="saveAge">
						</div>
						<div class="form-group">
							<label>地址</label> <input type="text" class="form-control"
								id="saveAddress">
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭
					</button>
					<button type="button" class="btn btn-primary" id="saveConfirmBtn">提交更改</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
</body>


<script type="text/javascript">

	$(document).ready(function() {
		$("button[name='toggle']").height(20);
		$("button[name='refresh']").height(20);
		$("#updateModal").modal('hide');
		$("#saveModel").modal('hide');
	});

	function del(id) {
		if (confirm("是否删除?")) {
			$.ajax({
				url : "deleteById",
				data : {
					"id" : id
				},
				success : function(data) {
					alert("删除成功!");
					//重新加载表格
					$("#table").bootstrapTable("refresh");
				}
			});
		} else {
		}
	}

	//编辑按钮点击事件
	var idGlobal = 0;
	function edit(id) {
		$("#updateModal").modal('show');
		idGlobal = id;
		//清楚输入框信息
		$("#name").val("");
		$("#age").val("");
		$("#address").val("");
		//初始化用户信息
		$.ajax({
			url : 'queryUserById',
			data : {
				'id' : id
			},
			success : function(ret) {
				$("#name").val(ret.name);
				$("#age").val(ret.age);
				$("#address").val(ret.address);
			}
		});		
	}
	
	//编辑模态框下确认按钮的点击事件
	$("#updateConfirmBtn").click(function() {
		$("#updateModal").modal('hide');
		$.ajax({
			url : "update",
			method : 'post',
			data : {
				id : idGlobal,
				name : $("#name").val(),
				age : $("#age").val(),
				address : $("#address").val()
			},
			success : function() {
				alert("修改成功!");
				//重新加载表格
				$("#table").bootstrapTable("refresh");
			}
		});
	});

	//添加按钮点击事件
	$("#btn_save").click(function() {
		//借用修改的模态框
		$("#saveModal").modal('show');
		//清楚输入框信息
		$("#saveName").val("");
		$("#saveAge").val("");
		$("#saveAddress").val("");		
	});
	
	//添加用户模态框下的确认按钮点击事件
	$("#saveConfirmBtn").click(function() {
		$("#saveModal").modal('hide');
		$.ajax({
			url : "save",
			method : 'post',
			datatype:'json',
			data : {
				id : 0,
				name : $("#saveName").val(),
				age : $("#saveAge").val(),
				address : $("#saveAddress").val()
			},
			success : function() {
				alert("添加成功!");
				//重新加载表格
				$("#table").bootstrapTable("refresh");
			}
		});
	});

	//删除按钮点击事件(可以批量删除)
	$("#btn_delete").click(function() {
		var list = $("table").bootstrapTable('getSelections');
		if (list == null || list.length <= 0) {
			alert("未选中任何项!");
		} else {
			var idList = new Array();
			for (var i = 0; i < list.length; i++) {
				idList[i] = list[i].id;
			}
			if (confirm("是否删除选中的数据?")) {
				$.ajax({
					url : "deleteByList",
					type : 'post',
					dataType : 'json',
					// 				contentType:"application/json", 
					data : {
						idList : idList
					},
					success : function(data) {
						alert("删除成功!");
						//重新加载表格
						$("#table").bootstrapTable("refresh");
					}
				});
			} else {
			}
		}
	});

	//搜索按钮点击事件
	$("#searchBtn").click(function(){

		$("#table").bootstrapTable("refresh");
		//清空搜索内容
// 		$("#selectForm").val('');
// 		$("#searchText").val('');
	});
	
	$("#table")
			.bootstrapTable(
					{
						url : "getPageInfo",
						clickToSelect : true,
						dataType : "json",
						pageSize : 5,
						pageList : [ 5, 10, 20 ],
						contentType : "application/x-www-form-urlencoded;charset=utf-8",
						method : 'get',
						dataField : "data",
						//是否显示详细视图和列表视图的切换按钮
						queryParams : function(params) {//自定义参数,这里的参数是传给后台的,我这是是分页用的  
							return {//这里的params是table提供的  
								offset : params.offset,//从数据库第几条记录开始  
								limit : params.limit,//找多少条
								searchType : $("#selectForm").val(),								
								searchText :$("#searchText").val()
							};
						},
						responseHandler : function(res) {
							//在ajax获取到数据,渲染表格之前,修改数据源
							return res;
						},
						columns : [
								{
									field : 'state',
								},
								{
									field : 'id',
									title : 'ID',
									align : 'center'
								},
								{
									field : 'name',
									title : '姓名',
									align : 'center'
								},
								{
									field : 'age',
									title : '年龄',
									align : 'center'
								},
								{
									field : 'address',
									title : '地址',
									align : 'center'
								},
								{
									title : '操作',
									field : 'id',
									align : 'center',
									formatter : function(value, row, index) {
										var e = '<a href="#" mce_href="#" onclick="edit(\''
												+ row.id + '\')">编辑</a> ';
										var d = '<a href="#" mce_href="#" onclick="del(\''
												+ row.id + '\')">删除</a> ';
										return e + d;
									}

								} ]
					});
</script>
</html>
为了方便起见,我把整个jsp文件都贴上来了,可以看到,在新增和修改用户的界面,我们使用Bootstrap的模态框来实现,点击编辑或者添加按钮分别会弹出相应的模态框,编辑按钮在弹出模态框后会自动加载用户的信息。其实,这些功能相对来说本质上都是一样的,通过点击某些按钮,填写某些必要的信息,然后通过AJAX向后台发送请求,后台接收到请求的url和一些必要的信息后,进行相应的操作,之后再返回相应的数据。

这里我要着重提一下的是搜索功能,搜索按钮点击后触发BootstrapTable的更新功能,那么更新时,向后台传递的信息就多了一项,那就是用户输入的搜索的信息,并加上用户选择的搜索的条件,在用户输入方面,我并没有的进行校验,其实校验也不是很难,本来想加上去的,但是在写博文时才记起来,所以算了。后台接收到前台传递来的之二写信息后,再返回相应的信息。

再看后台控制器部分:

BootstrapTableController.java

package controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import dao.UserDao;
import entity.User;

@Controller
public class BootstrapTableController {

	@RequestMapping("/getPageInfo")
	public @ResponseBody Map<String,Object> getPageInfo(int limit,int offset,String searchType,String searchText) throws UnsupportedEncodingException {
		searchText = new String(searchText.getBytes("ISO-8859-1"),"UTF-8"); 
		System.out.println("limit is:"+limit);
		System.out.println("offset is:"+offset);
		System.out.println("searchType is"+searchType);
		System.out.println("searchText is"+searchText);
		UserDao userDao = new UserDao();
		Map<String,Object> map = userDao.queryPageInfo(limit, offset,searchType,searchText);
		return map;
	}
	
	@RequestMapping("/deleteById")
	public @ResponseBody Map<String,Object> deleteById(@RequestParam("id")int id){
		UserDao userDao = new UserDao();
		userDao.deleteById(id);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status","success");
		return map;
	}
	
	@RequestMapping("deleteByList")
	public @ResponseBody Map<String,Object> deleteByList(@RequestParam("idList[]") List<Integer> idList){
		UserDao userDao = new UserDao();
		userDao.deleteByList(idList);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status","success");
		return map;
	}
	
	@RequestMapping("queryUserById")
	public @ResponseBody User queryUserById(int id){
		UserDao userDao = new UserDao();
		User user = userDao.queryById(id);
		return user;
	}
	
	@RequestMapping("update")
	public @ResponseBody Map<String,Object> update(User user){
		UserDao userDao = new UserDao();
		userDao.update(user);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status", "success");
		return map;
	}
	
	@RequestMapping("save")
	public @ResponseBody Map<String,Object> save(User user){
		UserDao userDao = new UserDao();
		userDao.save(user);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status", "success");
		return map;
	}
	
}
控制器部分没什么说的,再看Dao层:

UserDao.java:

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 com.mysql.jdbc.StringUtils;

import entity.User;

public class UserDao {

	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 searchType,String searchText) {
		Session session = this.getSession();
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtils.isNullOrEmpty(searchText)) {
			if("id".equals(searchType)) {
				String sql = "from User u where u.id = ?";
				int id = Integer.parseInt(searchText);
				List<User> userList = session.createQuery(sql).setInteger(0,id).getResultList();
				
				String sql2 = "select count(u.id) from User u where u.id = ?";
				int totalRecord = Integer.parseInt(session.createQuery(sql2).setInteger(0,id).uniqueResult().toString());
				
				map.put("total", totalRecord);
				map.put("data", userList);
			}else if("name".equals(searchType)) {
				String sql = "from User u where u.name like ?";
				Query query = session.createQuery(sql);
				query.setString(0,"%"+searchText+"%");
				query.setMaxResults(limit);
				query.setFirstResult(offset);
				List<User> userList = query.getResultList();
				
				String sql2 = "select count(*) from User u where u.name like ?";
				int totalRecord = Integer.parseInt(session.createQuery(sql2).setString(0,"%"+searchText+"%").uniqueResult().toString());
				
				map.put("total", totalRecord);
				map.put("data", userList);				
				
			}else if("age".equals(searchType)) {
				String sql = "from User u where u.age = ?";
				Query query = session.createQuery(sql);
				query.setInteger(0, Integer.parseInt(searchText));
				query.setMaxResults(limit);
				query.setFirstResult(offset);
				List<User> userList = query.getResultList();
				String sql2 = "select count(*) from User u where u.age = ?";
				int totalRecord = Integer.parseInt(session.createQuery(sql2).setInteger(0,Integer.parseInt(searchText)).uniqueResult().toString());
				
				map.put("total", totalRecord);
				map.put("data", userList);
			}else if("address".equals(searchType)) {
				String sql = "from User u where u.address like ?";
				Query query = session.createQuery(sql);
				query.setString(0,"%"+searchText+"%");
				query.setMaxResults(limit);
				query.setFirstResult(offset);
				List<User> userList = query.getResultList();
				
				String sql2 = "select count(*) from User u where u.address like ?";
				int totalRecord = Integer.parseInt(session.createQuery(sql2).setString(0,"%"+searchText+"%").uniqueResult().toString());
				
				map.put("total", totalRecord);
				map.put("data", userList);
			}
		}else {
			String sql = "from User";
			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.put("total", totalRecord);
			map.put("data", userList);			
		}
		session.close();
		return map;
	}
	
	//根据id查询
	public User queryById(int id) {
		Session session = this.getSession();
		User user = session.get(User.class, id);
		session.close();
		return user;
	}
	
	//根据id删除
	public void deleteById(int id) {
		Session session = this.getSession();
		User user = this.queryById(id);
		session.delete(user);
		Transaction tx = session.beginTransaction();
		tx.commit();
		session.close();
	}
	
	//批量删除
	public void deleteByList(List<Integer> idList) {
		Session session = this.getSession();
		for(Integer id : idList) {
			this.deleteById(id);					
		}
		session.close();
	}
	
	//修改
	public void update(User user) {
		Session session = this.getSession();
		session.update(user);	
		Transaction tx = session.beginTransaction();
		tx.commit();		
		session.close();
	}
	
	//新增
	public void save(User user) {
		Session session = this.getSession();
		session.save(user);
		Transaction tx = session.beginTransaction();
		tx.commit();
		session.close();
	}
}
Dao层也没什么说的,其他的文件在第一篇上已经都贴出来了,这里就不重复。

这样,一个基本的BootstrapTable的使用已经描述的差不多了,上运行截图。

【第二篇】 搞定BootstrapTable(后端使用SpringMVC+Hibernate)

【第二篇】 搞定BootstrapTable(后端使用SpringMVC+Hibernate)

【第二篇】 搞定BootstrapTable(后端使用SpringMVC+Hibernate)