1. 程式人生 > >SSM整合-02 資訊查詢

SSM整合-02 資訊查詢

專案完整實現程式碼下載地址:https://download.csdn.net/download/bingbeichen/10578683。

該部分主要實現員工資訊的查詢與顯示,主要實現步驟包括:

  • 訪問index.jsp頁面,該頁面傳送查詢員工列表的請求(URI為/emps);
  • 處理器EmployeeHandler來接收請求,查詢出員工資料;
  • 返回到/WEB-INF/views/emp-list.jsp頁面進行員工資訊的顯示;
  • 使用PageHelper分頁外掛完成分頁查詢功能。

###1. 分頁查詢後臺程式碼實現
第一步,訪問index.jsp頁面,在該頁面傳送查詢員工列表資料的請求,如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:forward page="/emps"></jsp:forward>

第二步,建立控制器EmployeeHandler來接收請求,查詢出員工資訊,如下:

// EmployeeHandler.java
@Controller
public class EmployeeHandler {

	@Autowired
	private EmployeeService employeeService;

	@RequestMapping("/emps")
	public String handleGetEmps() {
		// 查詢所有員工資訊(需要建立業務邏輯元件EmployeeService)
		List<Employee> emps = employeeService.getAll();
		// 返回到emp-list.jsp頁面進行顯示
		return "emp-list";
	}

}
// EmployeeService.java
@Service
public class EmployeeService {

	@Autowired
	private EmployeeMapper employeeMapper;

	public List<Employee> getAll() {
		List<Employee> emps = employeeMapper.selectByExampleWithDept(null);
		return emps;
	}
	
}

第三步, 使用PageHelper分頁外掛完成分頁查詢功能,該部分主要包括:
(1). 引入分頁外掛,即在pom.xml檔案中新增如下依賴

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.1.4</version>
</dependency>

(2). 在MyBatis的全域性配置檔案mybatis-config.xml中,配置攔截器外掛

<plugins>
	<!-- com.github.pagehelper為PageHelper類所在包名 -->
	<plugin interceptor="com.github.pagehelper.PageInterceptor">
		<!-- 分頁合理化引數,預設值為false。
			當為true時,pageNum<=0 時查詢第一頁, pageNum>pages時查詢最後一頁。 
		 -->
		<property name="reasonable" value="true"/>
	</plugin>
</plugins>

(3). 在控制器EmployeeHandler中進行分頁查詢,並將查詢結果封裝在Map中

@Controller
public class EmployeeHandler {

	@Autowired
	private EmployeeService employeeService;
	
	@RequestMapping("/emps")
	public String handleGetEmps(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Model model) {
		// 使用PageHelper元件獲取第pageNum頁,共6條內容
		PageHelper.startPage(pageNum, 6);
		// 緊跟的查詢操作即為分頁查詢
		List<Employee> emps = employeeService.getAll();
		// 使用PageInfo對分頁查詢結果進行封裝,以獲取分頁查詢的詳細資訊,並傳入可連續顯示的頁數
		PageInfo<Employee> pageInfo = new PageInfo<Employee>(emps, 6);
		// 將pageInfo物件傳遞到結果頁面
		model.addAttribute("pageInfo", pageInfo);
		return "emp-list";
	}

}

第四步,使用Spring單元測試測試分頁請求及其返回結果的正確性

package com.qiaobc.crud.test;

/**
 * Spring4測試時需要servlet3.0支援
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:applicationContext.xml",
		"file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml" })
public class CRUDTest {

	@Autowired
	private WebApplicationContext context;

	// 虛擬MVC請求,獲取請求結果
	private MockMvc mockMvc;

	@Before
	public void initMockMvc() {
		mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@Test
	public void testGetAll() throws Exception {
		// 模擬請求並獲取請求結果
		MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pageNum", "1")).andReturn();
		MockHttpServletRequest request = result.getRequest();
		PageInfo pageInfo = (PageInfo) request.getAttribute("pageInfo");
		System.out.println("當前頁碼:" + pageInfo.getPageNum());
		System.out.println("總頁碼數:" + pageInfo.getPages());
		System.out.println("總記錄數:" + pageInfo.getTotal());

		System.out.print("連續頁面:");
		int[] nums = pageInfo.getNavigatepageNums();
		for (int i : nums) {
			System.out.print(i + "  ");
		}
		System.out.println();

		// 獲取所有員工資訊
		List<Employee> emps = pageInfo.getList();
		for (Employee emp : emps) {
			System.out.println(emp.getLastName());
		}
	}
}

至此為止,分頁查詢的後臺程式碼和測試均已完成。


###2. 分頁查詢頁面搭建與資料顯示
基於Bootstrap前端框架搭建分頁頁面,並對分頁資料進行整理顯示,實現效果圖如下:
這裡寫圖片描述
查詢結果顯示頁面emp-list.jsp的具體實現程式碼:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>員工資訊顯示</title>
<%
	pageContext.setAttribute("WEB_PATH", request.getContextPath());
%>
<script type="text/javascript"
	src="${WEB_PATH }/static/javascript/jquery-3.3.1.min.js"></script>
<link
	href="${WEB_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
	rel="stylesheet">
<script
	src="${WEB_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

	<!-- 搭建顯示介面 -->
	<div class="container">
		<!-- 標題行 -->
		<div class="raw">
			<div class="col-md-12">
				<h1>SSM_CRUD</h1>
			</div>
		</div>
		<!-- 按鈕行 -->
		<div class="raw">
			<div class="col-md-4 col-md-offset-8">
				<button class="btn btn-primary">新增</button>
				<button class="btn btn-danger">刪除</button>
			</div>
		</div>
		<!-- 顯示錶格資料 -->
		<div class="raw">
			<div class="col-md-12">
				<table class="table table-striped">
					<tr>
						<th>工號</th>
						<th>姓名</th>
						<th>郵箱</th>
						<th>性別</th>
						<th>部門</th>
						<th>操作</th>
					</tr>
					<c:forEach items="${pageInfo.list }" var="emp">
						<tr>
							<td>${emp.id }</td>
							<td>${emp.lastName }</td>
							<td>${emp.email }</td>
							<td>${emp.gender == "F" ? "女" : "男" }</td>
							<td>${emp.dept.deptName }</td>
							<td>
								<button class="btn btn-info btn-sm">
									<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
									編輯
								</button>
								<button class="btn btn-danger btn-sm">
									<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
									刪除
								</button>
							</td>
						</tr>
					</c:forEach>
				</table>
			</div>
		</div>
		<!-- 顯示分頁資訊 -->
		<div class="raw">
			<!-- 分頁文字資訊 -->
			<div class="col-md-6">當前第${pageInfo.pageNum }頁,共有${pageInfo.pages }頁,總計${pageInfo.total }條記錄
			</div>
			<!-- 分頁條資訊 -->
			<div class="col-md-6">
				<nav aria-label="Page navigation">
					<ul class="pagination">
						<li><a href="${WEB_PATH }/emps?pageNum=1">首頁</a></li>
						<c:if test="${pageInfo.hasPreviousPage }">
							<li><a
								href="${WEB_PATH }/emps?pageNum=${pageInfo.pageNum - 1}"
								aria-label="Previous"> <span aria-hidden="true">&laquo;</span>
							</a></li>
						</c:if>
						<c:forEach items="${pageInfo.navigatepageNums }" var="pn">
							<c:if test="${pn == pageInfo.pageNum}">
								<li class="active"><span>${pn } <span
										class="sr-only">(current)</span></span></li>
							</c:if>
							<c:if test="${pn != pageInfo.pageNum}">
								<li><a href="${WEB_PATH }/emps?pageNum=${pn }">${pn }</a></li>
							</c:if>
						</c:forEach>
						<c:if test="${pageInfo.hasNextPage }">
							<li><a
								href="${WEB_PATH }/emps?pageNum=${pageInfo.pageNum + 1}"
								aria-label="Next"> <span aria-hidden="true">&raquo;</span>
							</a></li>
						</c:if>
						<li><a href="${WEB_PATH }/emps?pageNum=${pageInfo.pages }">尾頁</a></li>
					</ul>
				</nav>
			</div>
		</div>

	</div>

</body>
</html>

至此,員工資訊的分頁查詢及顯示功能已實現完畢,但該實現僅適用於瀏覽器-伺服器結構,若實現移動端與伺服器的互動則需要重新修改後臺程式碼,在此可直接返回分頁結果的JSON資料以使伺服器適配不同的客戶端。


###3. 返回分頁結果的JSON資料
通過JSON的形式返回分頁結果以實現員工資訊的查詢與顯示,主要步驟包括:

  • index.jsp頁面直接傳送Ajax請求進行員工分頁資料的查詢;
  • 伺服器將查出的資料,以JSON字串的形式返回給客戶端;
  • 客戶端可以使用javascript對JSON字串進行解析,並通過dom增刪改來顯示頁面;
  • 返回JSON字串串,可以實現客戶端的無關性。

首先,在pom.xml檔案中新增jackson包的依賴資訊

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.6</version>
</dependency>

然後,修改控制器的目標方法,使其返回封裝有分頁資訊的JSON字串

@Controller
public class EmployeeHandler {

	@Autowired
	private EmployeeService employeeService;
	
	@RequestMapping("/emps")
	@ResponseBody
	public Message handleGetEmpsRtnJson(@RequestParam(value = "pageNum", defaultValue="1") Integer pageNum, Model model) {
		PageHelper.startPage(pageNum, 6);
		List<Employee> list = employeeService.getAll();
		PageInfo pageInfo = new PageInfo(list, 6);
		// 返回帶狀態碼的JSON資料
		return Message.success().add("pageInfo", pageInfo);
	}
}
package com.qiaobc.crud.bean;
public class Message {
	
	// 狀態碼  100-成功  200-失敗
	private Integer code;
	
	// 提示資訊
	private String msg;
	
	// 待返回資料
	Map<String, Object> extend = new HashMap<String, Object>();
	
	// 成功
	public static Message success() {
		Message result = new Message();
		result.setCode(100);
		result.setMsg("操作成功");
		return result;
	}
	
	// 失敗
	public static Message fail() {
		Message result = new Message();
		result.setCode(200);
		result.setMsg("操作失敗");
		return result;
	}
	
	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Map<String, Object> getExtend() {
		return extend;
	}

	public void setExtend(Map<String, Object> extend) {
		this.extend = extend;
	}

	public Message add(String key, Object value) {
		this.getExtend().put(key, value);
		return this;
	}

}

最後,修改index.jsp顯示頁面,以解析返回的JSON字串,並顯示在頁面上

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>員工資訊顯示</title>
<%
	pageContext.setAttribute("WEB_PATH", request.getContextPath());
%>
<script type="text/javascript"
	src="${WEB_PATH }/static/javascript/jquery-3.3.1.min.js"></script>
<link
	href="${WEB_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
	rel="stylesheet">
<script
	src="${WEB_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

	<!-- 搭建顯示介面 -->
	<div class="container">
		<!-- 標題行 -->
		<div class="raw">
			<div class="col-md-12">
				<h1>SSM_CRUD</h1>
			</div>
		</div>
		<!-- 按鈕行 -->
		<div class="raw">
			<div class="col-md-4 col-md-offset-8">
				<button class="btn btn-primary">新增</button>
				<button class="btn btn-danger">刪除</button>
			</div>
		</div>
		<!-- 顯示錶格資料 -->
		<div class="raw">
			<div class="col-md-12">
				<table class="table table-striped" id="emps_table">
					<thead>
						<tr>
							<th>工號</th>
							<th>姓名</th>
							<th>郵箱</th>
							<th>性別</th>