mybatis-pagehelper-ajax-log分頁插件實現日誌分頁顯示

使用分頁插件(pagehelper)顯示日誌

整理於2020年02月17日

使用有道雲筆記md的第三天

開發工具:eclipse

  • sm-pagehelper-ajax-log(noSpringMVC)
  • ssm-pagehelper-ajax-log

目錄


使用分頁插件(pagehelper)顯示日誌

sm(noSpringMVC)

1. spring+mybatis+pagehelper+ajax(noSpringMVC) 分頁顯示日誌信息(傳參(無法排序)、調用靜態方法(startPage()) 兩種的方式)

1. 數據準備、導入jarweb.xmlspring配置文件(applicationContext.xml)

數據準備:登錄註冊項目的操作日誌表log

CREATE TABLE `log` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號',
 `pageinfo` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用戶操作信息',
 `ip` int(10) unsigned DEFAULT NULL COMMENT 'ip信息',
 `time` datetime DEFAULT NULL COMMENT '操作時間',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

導入jar包:
jar01 jar02

項目結構
sm項目結構
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>webzyspring-mybatis-pagehelper-log-ajax</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 上下文參數 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- 開啓-掃描組件 掃描註解 -->
	<context:component-scan base-package="com.zy.service.impl"></context:component-scan>
	<!-- 加載屬性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- dataSource -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- sqlSessionFactory -->
	<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="typeAliasesPackage" value="com.zy.pojo"></property>
		<!-- pagehelper攔截器插件配置 -->
		<property name="plugins">
	    	<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<!--使用下面的方式配置參數,一行配置一個 -->
						<value>
							helperDialect=mysql
					 		reasonable=true
					 		supportMethodsArguments=true
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>
	<!-- 掃描mapper -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zy.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="factory"></property>
	</bean>
	<!-- 事務管理器 -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 聲明式事務 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="ins*"/>
			<tx:method name="del*"/>
			<tx:method name="upd*"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- 配置AOP -->
	<aop:config>
		<aop:pointcut expression="execution(* com.zy.service.impl.*.*(..))" id="mypoint"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
	</aop:config>
	<!-- 使用cjlib動態代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbtest?useSSL=false
jdbc.username=root
jdbc.password=root

log4j.properties

log4j.rootCategory=INFO, CONSOLE
#log4j.rootCategory=INFO, CONSOLE ,LOGFILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss}  %m %n

#log4j.appender.LOGFILE=org.apache.log4j.FileAppender
#log4j.appender.LOGFILE.File=D:/my.log
#log4j.appender.LOGFILE.Append=true
#log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%m %n

2.pojo

Log.java

package com.zy.pojo;

public class Log {
	int id;
	String pageInfo;
	String ip;
	String time;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPageInfo() {
		return pageInfo;
	}
	public void setPageInfo(String pageInfo) {
		this.pageInfo = pageInfo;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time = time;
	}
	@Override
	public String toString() {
		return "Log [id=" + id + ", pageInfo=" + pageInfo + ", ip=" + ip + ", time=" + time + "]";
	}
}

3.持久層mapper

LogMapper.java

package com.zy.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.zy.pojo.Log;
public interface LogMapper {
	/**
	 * 使用調用靜態方法的方式
	 * @return
	 */
	@Select("select * from log")
	List<Log> selByPageStatic();
	/**
	 * 使用傳參的方式
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Select("select * from log")
	List<Log> selByPage(
			@Param("pageNum") int pageNum,
			@Param("pageSize") int pageSize);
}

4.業務層service

LogService.java

package com.zy.service;
import com.github.pagehelper.PageInfo;
import com.zy.pojo.Log;
public interface LogService {
	/**
	 * 通過調用靜態方法的方式
	 * @return
	 */
	PageInfo<Log> showLog();
	/**
	 * 通過傳參的方式
	 * @param pageNumStr
	 * @param pageSizeStr
	 * @return
	 */
	PageInfo<Log> showLog(int pageNum ,int pageSize );
}

LogServiceImpl.java

package com.zy.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageInfo;
import com.zy.mapper.LogMapper;
import com.zy.pojo.Log;
import com.zy.service.LogService;

@Service
public class LogServiceImpl implements LogService{
	@Resource
	private LogMapper mapper;
	@Override
	public PageInfo<Log> showLog() {
		PageInfo<Log> pi = new PageInfo<Log>(mapper.selByPageStatic());
		return pi;
	}
	@Override
	public PageInfo<Log> showLog(int pageNum, int pageSize) {
		PageInfo<Log> pi = new PageInfo<Log>(mapper.selByPage(pageNum, pageSize));
		return pi;
	}
}

5.控制器servlet

ShowLogServlet.java

package com.zy.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zy.pojo.Log;
import com.zy.service.LogService;
import com.zy.service.impl.LogServiceImpl;

@WebServlet("/showLog")
public class ShowLogServlet extends HttpServlet{
	private LogService logService;
	@Override
	public void init() throws ServletException {
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		logService = wac.getBean("logServiceImpl",LogServiceImpl.class);
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String pageNumStr = req.getParameter("pageNum");
		String pageSizeStr = req.getParameter("pageSize");
		String sortType = req.getParameter("sortType");
		int pageNum = 1;
		if (pageNumStr != null && !pageNumStr.equals("")) {
			pageNum = Integer.parseInt(pageNumStr.trim());
		}
		int pageSize = 10;
		if (pageSizeStr != null && !pageSizeStr.equals("")) {
			pageSize = Integer.parseInt(pageSizeStr.trim());
		}
		PageInfo<Log> pi ;
		if(sortType!=null && !sortType.trim().equals("") && //排序參數合法
				(sortType.trim().equals("asc") ||sortType.trim().equals("desc")) ) {
			PageHelper.startPage(pageNum,pageSize,"id "+sortType.trim());
			pi = logService.showLog();
		}else {
//			PageHelper.startPage(pageNum,pageSize);
//			pi = logService.showLog();
			//如果沒有排序參數的話,就使用傳參的方式
			pi = logService.showLog(pageNum, pageSize);
		}
		//獲取到排序方式或者判斷prePage與nextPage的大小就知道是按什麼排序了
		//String orderBy = ((Page)pi.getList()).getOrderBy();
		//使用Ajax    設置響應內容
		resp.setContentType("application/json;charset=utf-8");
		PrintWriter out = resp.getWriter();
		//對象轉json
		ObjectMapper mapper = new ObjectMapper();
		out.println(mapper.writeValueAsString(pi));
		out.flush();
		out.close();
	}
}

6.視圖層jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
 <head>
  <base href="<%=basePath%>">
  <meta charset="UTF-8">
  <title>日誌顯示</title>
   <style>
table.hovertable {
	font-size: 13px;
	color: #333;
	border-width: 1px;
	border-color: #999;
	border-collapse: collapse;
	width: auto;
	margin: 0 auto;
}

table.hovertable th {
	background-color: #c3dde0;
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
}

table.hovertable tr {
	background-color: #d4e3e5;
}

table.hovertable td {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
	text-align: center;
}

button {
	border: 1px solid transparent;
	color: #457eff;
	background-color: #fff;
	border-color: #457eff;
	border-radius:10px;
}

button:hover {
	border: 1px solid transparent;
	border-color: #ffae00;
	color: rgb(255, 0, 157);
}

/* 分頁顯示 - 切換當前頁 的css  記得帶上 a a:hover的樣式 */
a {
	text-decoration: none;
	font-size: 14px;
	color: #457eff;
}

a:hover {
	text-decoration: none;
	color: rgb(255, 0, 157);
}

.page {
    /* line-height: 16px; */
    text-align: right;
    padding: 8px 0;
    /* margin-right: 1px; */
    height: 44px;
    /* border: 1px solid #e6e6e6; */
    border-top: none;
    margin: 0;
}
.dataTables_paginate {
    display: block;
    height: 30px;
    margin-bottom: 10px;
    margin-top: 15px;
    position: relative;
}
.page div {
    float: right;
}
.page .Pcurrent {
    color: #fff;
    background: #20a53a;
    cursor: default;
    border-color: #20a53a;
}
.page span, .page a {
    display: inline-block;
    height: 28px;
    line-height: 28px;
    padding: 0 10px;
    font-family: "Arial";
    font-size: 13px;
    color: #666;
    float: left;
    border: 1px solid #ececec;
    border-right: none;
}
.page a:hover {
    background: #e8e8e8;
    color: #20a53a;
    text-shadow: 0 1px 0 #fff;
    cursor: pointer;
}

/* 設置每頁顯示的條數 */
.Pcount-item {
    border-right: 1px solid #ececec;
}
input, textarea, select {
    font-size: 100%;
    font-family: inherit;
}
button, input, select, textarea {
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
}
button, select {
    text-transform: none;
}
button, input, optgroup, select, textarea {
    margin: 0;
    font: inherit;
    color: inherit;
}
</style>
  <script type="text/javascript" src="<%=path %>/js/jquery-3.4.1.js"></script>
  <script type="text/javascript">
$(function() {
	//當前頁
	var pageNum = 1;
	//當前頁的數量
	var pageSize = 10;
	
	//當前頁的數量
	var size = 0;
	//總數據條數
	var total = 0;
	//總頁數
	var pages = 0;
	//導航頁碼數(默認爲8)
	var navigatePages = 0;
	//導航頁碼(默認有8個)
	var navigatepageNums = new Array();
	//前一頁
	var prePage =1;
	//下一頁
	var nextPage = 1;
	
	//select數組(下拉框)
	var select = ["10","50","100","200","500","1000","2000"];
	//排序方式
	var sortType = "desc";
	
	//默認調用一次,加載數據
	getMyData();
	
	//首頁
	$("#navigate").on("click",".Pstart",function(){
		pageNum = 1;
		getMyData();
		return false;
	});
	//尾頁
	$("#navigate").on("click",".Pend",function(){
		pageNum = pages;
		getMyData();
		return false;
	});
	//上一頁
	$("#navigate").on("click",".Ppren",function() {
		pageNum = prePage;
		getMyData();
		return false;
	});
	//下一頁
	$("#navigate").on("click",".Pnext",function() {
		pageNum = nextPage;
		getMyData();
		return false;
	});
	//跳轉到指定頁
	$("#navigate").on("click",".Pnum",function(){
		pageNum = $(this).html();
		getMyData();
		return false;
	});
	//下拉框事件
	$("#navigate").on("change","#pcount-item",function(){
		//如果當前頁大於或等於改變後的頁就顯示第一頁
		if(pageNum >= (total/$(this).val()+1)){
			pageNum = 1; 
		}
		pageSize = $(this).val();
		getMyData(); 
		return false; 
	});
	//正序排序事件
	$("#asc").on("click",function(){
		sortType = "asc";
		pageNum = 1;
		getMyData();
		return false;
	});
	//倒序排序事件
	$("#desc").on("click",function(){
		sortType = "desc";
		pageNum = 1;
		getMyData();
		return false;
	});
	
	function getMyData(){
		//$.post(url,參數,success回調方法,dataType)
		$.post("showLog",{"pageSize":pageSize,"pageNum":pageNum,"sortType":sortType},function(data){
			pages = data.pages;
			prePage = data.prePage;
			nextPage = data.nextPage;
			pageNum = data.pageNum;
			pageSize = data.pageSize;
			total = data.total;
			
			// 日誌表格
			var result = "";
			for (var i = 0; i < data.list.length; i++) {
				result+="<tr >";
				result+="<td>"+data.list[i].id+"</td>";
				result+="<td>"+data.list[i].time+"</td>";
				result+="<td>"+data.list[i].ip+"</td>";
				result+="<td colspan='2'>"+data.list[i].pageInfo+"</td>";
				result+="</tr>";
			}
			$("#mytbody").html(result);
			
			//導航欄
			var navigate = "";
			if(!data.isFirstPage){
				navigate += "<a class='Pstart' href=''>首頁</a><a class='Ppren' href=''>上一頁</a>";
			}
			for (var i = 0; i < data.navigatepageNums.length; i++) {
				if(data.navigatepageNums[i]==data.pageNum){
					navigate += "<span class='Pcurrent'>"+data.navigatepageNums[i]+"</span>";
				}else{
					navigate += "<a class='Pnum' href=''>"+data.navigatepageNums[i]+"</a>";
				}
			}
			if(!data.isLastPage){
				navigate += "<a class='Pnext' href=''>下一頁</a><a class='Pend' href=''>尾頁</a>";
			}
			navigate += "<span class='Pcount'>共"+data.pages+"頁"+data.total+"條數據</span>";
			
			//下拉框
			navigate += "<span class='Pcount-item'>每頁<select id='pcount-item' style='margin-left: 3px;margin-right: 3px;border:#ddd 1px solid' class='showRow'>";
			for(var i = 0; i< select.length; i++){
				//如果當前下拉框的值是當前頁碼,那麼就選中該值
				if(select[i]==pageSize){
					navigate += "<option value='"+select[i]+"' selected=''>"+select[i]+"</option>";
				}else{
					navigate += "<option value='"+select[i]+"'>"+select[i]+"</option>";
				}
			}
			navigate += "</select>條	</span>";
			$("#navigate").html(navigate);
		})
	}
});
  </script>
 </head>
 <body>
 <h3 align="center">使用mybatis-pagehelper插件分頁</h3>
 <hr>
 <div>
	<table class="hovertable">
	<tr>	
		<th>編號</th>
		<th>時間</th>
		<th>IP</th>
		<th>操作	</th>
		<th>
			<button type="button" style="">
				<a href="" id="asc" ></a>
			</button>
			<button type="button" style="">
				<a href="" id="desc" ></a>
			</button>
			<button type="button">
				<a href="<%=path%>/">返回主頁</a>
			</button>
		</th>
	</tr>
	<tbody id="mytbody"></tbody>
	</table>
  </div>
  <br>
  <!-- 導航頁碼 -->
  <div class="dataTables_paginate paging_bootstrap page logsBody" style="margin-bottom:0">
  	<div id="navigate">
  	</div>
  </div>
 </body>
</html>

ssm

2. ssm+pagehelper+ajax分頁顯示日誌信息

1. 數據準備、導入jarweb.xmlspring配置文件(applicationContext.xml)

數據準備:登錄註冊項目的操作日誌表log

CREATE TABLE `log` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號',
 `pageinfo` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用戶操作信息',
 `ip` int(10) unsigned DEFAULT NULL COMMENT 'ip信息',
 `time` datetime DEFAULT NULL COMMENT '操作時間',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

導入jar包:
jar01 jar02

項目結構
ssm項目結構
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>webzyspring-mybatis-pagehelper-log-ajax</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 上下文參數 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 前端控制器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 字符編碼攔截器 -->
  <filter>
  	<filter-name>encoding</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- 開啓-掃描組件 掃描註解(service) -->
	<context:component-scan base-package="com.zy.service.impl"></context:component-scan>
	<!-- 加載屬性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- dataSource -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- sqlSessionFactory -->
	<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="typeAliasesPackage" value="com.zy.pojo"></property>
		<!-- pagehelper攔截器插件配置 -->
		<property name="plugins">
	    	<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<!--使用下面的方式配置參數,一行配置一個 -->
						<value>
							helperDialect=mysql
					 		reasonable=true
					 		supportMethodsArguments=true
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>
	<!-- 掃描mapper -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zy.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="factory"></property>
	</bean>
	<!-- 事務管理器 -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 聲明式事務 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="ins*"/>
			<tx:method name="del*"/>
			<tx:method name="upd*"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- 配置AOP -->
	<aop:config>
		<aop:pointcut expression="execution(* com.zy.service.impl.*.*(..))" id="mypoint"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
	</aop:config>
	<!-- 使用cjlib動態代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 開啓掃描註解(mapper) -->
	<context:component-scan base-package="com.zy.controller"></context:component-scan>
	<!-- 註解驅動 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 靜態資源 -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/img/" mapping="/img/**"></mvc:resources>
</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbtest?useSSL=false
jdbc.username=root
jdbc.password=root

log4j.properties

log4j.rootCategory=INFO, CONSOLE
#log4j.rootCategory=INFO, CONSOLE ,LOGFILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss}  %m %n

#log4j.appender.LOGFILE=org.apache.log4j.FileAppender
#log4j.appender.LOGFILE.File=D:/my.log
#log4j.appender.LOGFILE.Append=true
#log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%m %n

2.pojo

Log.java

3.持久層mapper(同上)

LogMapper.java

4.業務層service(同上)

LogService.java

LogServiceImpl.java

5.控制器controller(同上)

ShowLogServlet.java

package com.zy.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zy.pojo.Log;
import com.zy.service.LogService;

@Controller
public class ShowLogController {

	@Resource
	private LogService logServiceImpl;
	
	@RequestMapping("/showLog")
	@ResponseBody
	public PageInfo<Log> showByPage(String pageNum,String pageSize,String sortType) {
		//初始化分頁參數
		int pageNumInt = 1;
		if (pageNum != null && !pageNum.equals("")) {
			pageNumInt = Integer.parseInt(pageNum.trim());
		}
		int pageSizeInt = 10;
		if (pageSize != null && !pageSize.equals("")) {
			pageSizeInt = Integer.parseInt(pageSize.trim());
		}
		PageInfo<Log> pi ;
		if(sortType!=null && !sortType.trim().equals("") && //排序參數是否合法
				(sortType.trim().equals("asc") ||sortType.trim().equals("desc")) ) {
			PageHelper.startPage(pageNumInt,pageSizeInt,"id "+sortType.trim());
			pi = logServiceImpl.showLog();
		}else {
//			PageHelper.startPage(pageNum,pageSize);
//			pi = logService.showLog();
			//如果沒有排序參數的話,就使用傳參的方式
			pi = logServiceImpl.showLog(pageNumInt, pageSizeInt);
		}
		//獲取到排序方式
		//String orderBy = ((Page)pi.getList()).getOrderBy();
		return pi;
	}
}

6.視圖層jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    
    %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html>
 <head>
  <base href="<%=basePath%>">
  <meta charset="UTF-8">
  <title>日誌顯示</title>
   <style>
table.hovertable {
	font-size: 13px;
	color: #333;
	border-width: 1px;
	border-color: #999;
	border-collapse: collapse;
	width: auto;
	margin: 0 auto;
}

table.hovertable th {
	background-color: #c3dde0;
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
}

table.hovertable tr {
	background-color: #d4e3e5;
}

table.hovertable td {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
	text-align: center;
}

button {
	border: 1px solid transparent;
	color: #457eff;
	background-color: #fff;
	border-color: #457eff;
	border-radius:10px;
}

button:hover {
	border: 1px solid transparent;
	border-color: #ffae00;
	color: rgb(255, 0, 157);
}



/* 分頁顯示 - 切換當前頁 的css  記得帶上 a a:hover的樣式 */
a {
	text-decoration: none;
	font-size: 14px;
	color: #457eff;
}

a:hover {
	text-decoration: none;
	color: rgb(255, 0, 157);
}

.page {
    /* line-height: 16px; */
    text-align: right;
    padding: 8px 0;
    /* margin-right: 1px; */
    height: 44px;
    /* border: 1px solid #e6e6e6; */
    border-top: none;
    margin: 0;
}
.dataTables_paginate {
    display: block;
    height: 30px;
    margin-bottom: 10px;
    margin-top: 15px;
    position: relative;
}
.page div {
    float: right;
}
.page .Pcurrent {
    color: #fff;
    background: #20a53a;
    cursor: default;
    border-color: #20a53a;
}
.page span, .page a {
    display: inline-block;
    height: 28px;
    line-height: 28px;
    padding: 0 10px;
    font-family: "Arial";
    font-size: 13px;
    color: #666;
    float: left;
    border: 1px solid #ececec;
    border-right: none;
}
.page a:hover {
    background: #e8e8e8;
    color: #20a53a;
    text-shadow: 0 1px 0 #fff;
    cursor: pointer;
}

/* 設置每頁顯示的條數 */
.Pcount-item {
    border-right: 1px solid #ececec;
}
input, textarea, select {
    font-size: 100%;
    font-family: inherit;
}
button, input, select, textarea {
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
}
button, select {
    text-transform: none;
}
button, input, optgroup, select, textarea {
    margin: 0;
    font: inherit;
    color: inherit;
}
</style>
  <script type="text/javascript" src="<%=path %>/js/jquery-3.4.1.js"></script>
  <script type="text/javascript">
$(function() {
	//當前頁
	var pageNum = 1;
	//當前頁的數量
	var pageSize = 10;
	
	//當前頁的數量
	var size = 0;
	//總數據條數
	var total = 0;
	//總頁數
	var pages = 0;
	//導航頁碼數(默認爲8)
	var navigatePages = 0;
	//導航頁碼(默認有8個)
	var navigatepageNums = new Array();
	//前一頁
	var prePage =1;
	//下一頁
	var nextPage = 1;
	
	//select數組(下拉框)
	var select = ["10","50","100","200","500","1000","2000"];
	//排序方式
	var sortType = "desc";
	
	
	//默認調用一次,加載數據
	getMyData();
	
	//首頁
	$("#navigate").on("click",".Pstart",function(){
		pageNum = 1;
		getMyData();
		return false;
	});
	//尾頁
	$("#navigate").on("click",".Pend",function(){
		pageNum = pages;
		getMyData();
		return false;
	});
	//上一頁
	$("#navigate").on("click",".Ppren",function() {
		pageNum = prePage;
		getMyData();
		return false;
	});
	//下一頁
	$("#navigate").on("click",".Pnext",function() {
		pageNum = nextPage;
		getMyData();
		return false;
	});
	//跳轉到指定頁
	$("#navigate").on("click",".Pnum",function(){
		pageNum = $(this).html();
		getMyData();
		return false;
	});
	//下拉框事件
	$("#navigate").on("change","#pcount-item",function(){
		//如果當前頁大於或等於改變後的頁就顯示第一頁
		if(pageNum >= (total/$(this).val()+1)){
			pageNum = 1; 
		}
		pageSize = $(this).val();
		getMyData(); 
		return false; 
	});
	//正序排序事件
	$("#asc").on("click",function(){
		sortType = "asc";
		pageNum = 1;
		getMyData();
		return false;
	});
	//倒序排序事件
	$("#desc").on("click",function(){
		sortType = "desc";
		pageNum = 1;
		getMyData();
		return false;
	});
	
	function getMyData(){
		//$.post(url,參數,success回調方法,dataType)
		$.post("showLog",{"pageSize":pageSize,"pageNum":pageNum,"sortType":sortType},function(data){
			pages = data.pages;
			prePage = data.prePage;
			nextPage = data.nextPage;
			pageNum = data.pageNum;
			pageSize = data.pageSize;
			total = data.total;
			
			// 日誌表格
			var result = "";
			for (var i = 0; i < data.list.length; i++) {
				result+="<tr >";
				result+="<td>"+data.list[i].id+"</td>";
				result+="<td>"+data.list[i].time+"</td>";
				result+="<td>"+data.list[i].ip+"</td>";
				result+="<td colspan='2'>"+data.list[i].pageInfo+"</td>";
				result+="</tr>";
			}
			$("#mytbody").html(result);
			
			//導航欄
			var navigate = "";
			if(!data.isFirstPage){
				navigate += "<a class='Pstart' href=''>首頁</a><a class='Ppren' href=''>上一頁</a>";
			}
			for (var i = 0; i < data.navigatepageNums.length; i++) {
				if(data.navigatepageNums[i]==data.pageNum){
					navigate += "<span class='Pcurrent'>"+data.navigatepageNums[i]+"</span>";
				}else{
					navigate += "<a class='Pnum' href=''>"+data.navigatepageNums[i]+"</a>";
				}
			}
			if(!data.isLastPage){
				navigate += "<a class='Pnext' href=''>下一頁</a><a class='Pend' href=''>尾頁</a>";
			}
			navigate += "<span class='Pcount'>共"+data.pages+"頁"+data.total+"條數據</span>";
			
			//下拉框
			navigate += "<span class='Pcount-item'>每頁<select id='pcount-item' style='margin-left: 3px;margin-right: 3px;border:#ddd 1px solid' class='showRow'>";
			for(var i = 0; i< select.length; i++){
				//如果當前下拉框的值是當前頁碼,那麼就選中該值
				if(select[i]==pageSize){
					navigate += "<option value='"+select[i]+"' selected=''>"+select[i]+"</option>";
				}else{
					navigate += "<option value='"+select[i]+"'>"+select[i]+"</option>";
				}
			}
			navigate += "</select>條	</span>";
			$("#navigate").html(navigate);
		})
	}
});
  </script>
 </head>
 <body>
 <h3 align="center">使用ssm-pagehelper插件分頁-ajax</h3>
 <hr>
 <div>
	<table class="hovertable">
	<tr>	
		<th>編號</th>
		<th>時間</th>
		<th>IP</th>
		<th>操作	</th>
		<th>
			<button type="button" style="">
				<a href="" id="asc" ></a>
			</button>
			<button type="button" style="">
				<a href="" id="desc" ></a>
			</button>
			<button type="button">
				<a href="<%=path%>/">返回主頁</a>
			</button>
		</th>
	</tr>
	<tbody id="mytbody"></tbody>
	</table>
  </div>
  <br>
  <!-- 導航頁碼 -->
  <div class="dataTables_paginate paging_bootstrap page logsBody" style="margin-bottom:0">
  	<div id="navigate">
  	</div>
  </div>
 </body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章