林炳文Evankaka原創作品。轉載請注明出處http://blog.csdn.net/evankaka
摘要:本文實現了一個后台由Spring+Mybatis+SpringMVC組成,分頁采用PageHelper,前台展示使用bootstrap-paginator來顯示效果的分頁實例。整個項目由maven構成。這里主要講了分頁的實例,框架怎么搭建就不再說明,主要是在這里的基礎上來增加分頁功能的。注意,此文是在這個基礎 Spring+Mybatis+SpringMVC+Maven+MySql搭建實例 之上來做分頁的,建議文中看不懂的配置可以看看這里。
最后的結果如下:
環境:jdk1.6
Tomcat 7.0
Eclipse luna/windows 7
一、后台PageHelper使用
PageHelper:https://github.com/pagehelper/Mybatis-PageHelper
1、引入jar包
- <!-- 添加分布插件的包pagehelper -->
- <dependency>
- <groupId>com.github.pagehelper</groupId>
- <artifactId>pagehelper</artifactId>
- <version>4.0.0</version>
- </dependency>
2.mybatis-config.xml中添加插件
- <plugins>
- <!-- com.github.pagehelper為PageHelper類所在包名 -->
- <plugin interceptor="com.github.pagehelper.PageHelper">
- <property name="dialect" value="mysql"/>
- <!-- 該參數默認為false -->
- <!-- 設置為true時,會將RowBounds第一個參數offset當成pageNum頁碼使用 -->
- <!-- 和startPage中的pageNum效果一樣-->
- <property name="offsetAsPageNum" value="true"/>
- <!-- 該參數默認為false -->
- <!-- 設置為true時,使用RowBounds分頁會進行count查詢 -->
- <property name="rowBoundsWithCount" value="true"/>
- <!-- 設置為true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果 -->
- <!-- (相當於沒有執行分頁查詢,但是返回結果仍然是Page類型)-->
- <property name="pageSizeZero" value="true"/>
- <!-- 3.3.0版本可用 - 分頁參數合理化,默認false禁用 -->
- <!-- 啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最后一頁 -->
- <!-- 禁用合理化時,如果pageNum<1或pageNum>pages會返回空數據 -->
- <property name="reasonable" value="false"/>
- <!-- 3.5.0版本可用 - 為了支持startPage(Object params)方法 -->
- <!-- 增加了一個`params`參數來配置參數映射,用於從Map或ServletRequest中取值 -->
- <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默認值 -->
- <!-- 不理解該含義的前提下,不要隨便復制該配置 -->
- <property name="params" value="pageNum=start;pageSize=limit;"/>
- </plugin>
- </plugins>
這樣子就引入進來了,接下來就是來開始分頁功能的實現
3、mapper文件中添加如下一個方法:
- <select id="selectUserByUserName" parameterType="java.lang.String" resultMap="BaseResultMap">
- SELECT *
- FROM t_user
- WHERE 1 = 1
- <if test="userName != null and userName !=''">
- AND USER_NAME = #{userName,jdbcType=VARCHAR}
- </if>
- ORDER BY USER_ID
- </select>
注意,這里的返回其實是一個list
- <!--設置domain類和數據庫中表的字段一一對應,注意數據庫字段和domain類中的字段名稱不致,此處一定要! -->
- <resultMap id="BaseResultMap" type="com.lin.domain.User">
- <id column="USER_ID" property="userId" jdbcType="INTEGER" />
- <result column="USER_NAME" property="userName" jdbcType="CHAR" />
- <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
- <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
- </resultMap>
4、然后就是dao類
- /**
- *
- * @author linbingwen
- * @since 2015年10月22日
- * @param userName
- * @return
- */
- List<User> selectUserByUserName(@Param("userName") String userName);
這里一定的記得加@Param("userName")
接下來就可以在service層中添加分頁查詢的的接口了
5、接口類
- /**
- *
- * @author linbingwen
- * @since 2015年10月23日
- * @param userName 查詢條件,可為空
- * @param pageNo 查詢條件,可為空,默認取1
- * @param pageSize 查詢條件,可為空,默認取10
- * @return
- */
- PagedResult<User> queryByPage(String userName,Integer pageNo,Integer pageSize);
6、實現類
- public PagedResult<User> queryByPage(String userName,Integer pageNo,Integer pageSize ) {
- pageNo = pageNo == null?1:pageNo;
- pageSize = pageSize == null?10:pageSize;
- PageHelper.startPage(pageNo,pageSize); //startPage是告訴攔截器說我要開始分頁了。分頁參數是這兩個。
- return BeanUtil.toPagedResult(userDao.selectUserByUserName(userName));
- }
這里就可以直接在返回里頭使用了PageHelper,這里userDao.selectUserByUserName(userName)的返回是一個list
其中,PagedResult是我自己封裝的一個分頁結果類
- package com.lin.util;
- import java.util.List;
- import com.lin.dto.BaseEntity;
- /**
- * 功能概要:
- *
- * @author linbingwen
- * @since 2015年10月23日
- */
- public class PagedResult<T> extends BaseEntity {
- /*serialVersionUID*/
- private static final long serialVersionUID = 1L;
- private List<T> dataList;//數據
- private long pageNo;//當前頁
- private long pageSize;//條數
- private long total;//總條數
- private long pages;//總頁面數目
- public List<T> getDataList() {
- return dataList;
- }
- public void setDataList(List<T> dataList) {
- this.dataList = dataList;
- }
- public long getPageNo() {
- return pageNo;
- }
- public void setPageNo(long pageNo) {
- this.pageNo = pageNo;
- }
- public long getPageSize() {
- return pageSize;
- }
- public void setPageSize(long pageSize) {
- this.pageSize = pageSize;
- }
- public long getTotal() {
- return total;
- }
- public void setTotal(long total) {
- this.total = total;
- }
- public long getPages() {
- return pages;
- }
- public void setPages(long pages) {
- this.pages = pages;
- }
- }
這是它的基類
- package com.lin.dto;
- import java.io.Serializable;
- import java.lang.reflect.Method;
- import java.lang.reflect.Modifier;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- *
- * <b>類說明:</b>bean基類
- *
- * <p>
- * <b>詳細描述:</b>
- *
- * @author costin_law
- * @since 2014-5-5
- */
- public abstract class BaseEntity implements Serializable{
- private static final long serialVersionUID = 1L;
- private static Map<Class<?>,PropertyInfo[]> class2Props = new HashMap<Class<?>,PropertyInfo[]>(128);
- @Override
- public String toString() {
- PropertyInfo[] props = class2Props.get(this.getClass());
- if( props == null ){
- props = getProps(this.getClass());
- }
- StringBuilder builder = new StringBuilder(1024);
- boolean isFirst = true;
- for (int i = 0, n = props.length; i < n; i++) {
- try {
- PropertyInfo propInfo = props[i];
- Object value = propInfo.getMethod.invoke(this, new Object[0]);
- if (isFirst)
- isFirst = false;
- else
- builder.append(",");
- builder.append(propInfo.propName);
- builder.append(":");
- if (value instanceof String)
- builder.append("\"");
- builder.append(value);
- if (value instanceof String)
- builder.append("\"");
- } catch (Exception e) {
- // ignore
- }
- }
- return "{" + builder.toString() + "}";
- }
- private static PropertyInfo[] getProps(Class<? extends BaseEntity> clazz) {
- PropertyInfo[] props;
- Method[] allMethods = clazz.getMethods();
- List<PropertyInfo> propList = new ArrayList<PropertyInfo>();
- for (int i = 0, n = allMethods.length; i < n; i++) {
- try {
- Method method = allMethods[i];
- if ((method.getModifiers() & Modifier.PUBLIC) == 1
- && method.getDeclaringClass() != Object.class
- && (method.getParameterTypes() == null || method
- .getParameterTypes().length == 0)) {
- String methodName = method.getName();
- if (methodName.startsWith("get") || methodName.startsWith("is") ) {
- PropertyInfo propInfo = new PropertyInfo();
- propInfo.getMethod = method;
- if (methodName.startsWith("get")) {
- propInfo.propName = methodName.substring(3, 4).toLowerCase()
- + methodName.substring(4);
- } else if (methodName.startsWith("is")) {
- propInfo.propName = methodName.substring(2, 3).toLowerCase()
- + methodName.substring(3);
- }
- propList.add(propInfo);
- }
- }
- }catch(Exception e){
- }
- }
- props = new PropertyInfo[propList.size()];
- propList.toArray(props);
- class2Props.put(clazz, props);
- return props;
- }
- static class PropertyInfo{
- Method getMethod;
- String propName;
- }
- }
BeanUtil是一個將PageHelper返回的list轉成pageResult的工具
- package com.lin.util;
- import java.util.List;
- import com.github.pagehelper.Page;
- import com.lin.util.PagedResult;
- /**
- * 功能概要:
- *
- * @author linbingwen
- * @since 2015年10月22日
- */
- public class BeanUtil {
- public static <T> PagedResult<T> toPagedResult(List<T> datas) {
- PagedResult<T> result = new PagedResult<T>();
- if (datas instanceof Page) {
- Page page = (Page) datas;
- result.setPageNo(page.getPageNum());
- result.setPageSize(page.getPageSize());
- result.setDataList(page.getResult());
- result.setTotal(page.getTotal());
- result.setPages(page.getPages());
- }
- else {
- result.setPageNo(1);
- result.setPageSize(datas.size());
- result.setDataList(datas);
- result.setTotal(datas.size());
- }
- return result;
- }
- }
7、這樣就好了,可以跑單元測試了
- /**
- * 分頁測試
- * @author linbingwen
- * @since 2015年10月22日
- */
- @Test
- public void queryByPage(){
- PagedResult<User> pagedResult = userService.queryByPage(null,1,10);//null表示查全部
- logger.debug("查找結果" + pagedResult);
- }
輸出結果:
看不清的話看下面
查找結果{total:46,dataList:Page{pageNum=1, pageSize=10, startRow=0, endRow=10, total=46, pages=5, reasonable=false,
pageSizeZero=true},pageNo:1,pageSize:10,pages:5}
其中的dataList中存放的就是數據
打個斷點看下就知道了:
二、前台展示分頁結果
前台展示主要使用了bootstrap-paginator,這里的原理其實就是將上面查出來的結果,轉換成json數據傳給前台,然后前台再根據條數和分頁數目、總目生成表格,同時每次點擊對應的按鈕都發送一個ajax請求到后台查詢應對的數據,前台每次發送到后台都會包含分頁數目、查詢條件
1、Controller層的基類
這個基類主要實現了將數據轉成json
引用到的jar包如下:
- <!-- 添加json的依賴包 -->
- <dependency>
- <groupId>net.sf.json-lib</groupId>
- <artifactId>json-lib</artifactId>
- <version>2.3</version>
- <classifier>jdk15</classifier>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-commons</artifactId>
- <version>1.6.1.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-jpa</artifactId>
- <version>1.4.1.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.1.34</version>
- </dependency>
基類如下:
- package com.lin.controller;
- import com.lin.common.HttpConstants;
- import com.lin.json.JsonDateValueProcessor;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- import net.sf.json.JsonConfig;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.util.Date;
- /**
- * Controller基類
- */
- public class BaseController {
- protected Logger logger = LoggerFactory.getLogger(this.getClass());
- protected final static String DATE_FORMATE = "yyyy-MM-dd";
- /**
- * 返回服務端處理結果
- * @param obj 服務端輸出對象
- * @return 輸出處理結果給前段JSON格式數據
- * @author YANGHONGXIA
- * @since 2015-01-06
- */
- public String responseResult(Object obj){
- JSONObject jsonObj = null;
- if(obj != null){
- logger.info("后端返回對象:{}", obj);
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
- jsonObj = JSONObject.fromObject(obj, jsonConfig);
- logger.info("后端返回數據:" + jsonObj);
- if(HttpConstants.SERVICE_RESPONSE_SUCCESS_CODE.equals(jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_FLAG))){
- jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
- jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
- }else{
- jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
- String errMsg = jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_MSG);
- jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errMsg==null?HttpConstants.SERVICE_RESPONSE_NULL:errMsg);
- }
- }
- logger.info("輸出結果:{}", jsonObj.toString());
- return jsonObj.toString();
- }
- /**
- * 返回成功
- * @param obj 輸出對象
- * @return 輸出成功的JSON格式數據
- */
- public String responseSuccess(Object obj){
- JSONObject jsonObj = null;
- if(obj != null){
- logger.info("后端返回對象:{}", obj);
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
- jsonObj = JSONObject.fromObject(obj, jsonConfig);
- logger.info("后端返回數據:" + jsonObj);
- jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
- jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
- }
- logger.info("輸出結果:{}", jsonObj.toString());
- return jsonObj.toString();
- }
- /**
- * 返回成功
- * @param obj 輸出對象
- * @return 輸出成功的JSON格式數據
- */
- public String responseArraySuccess(Object obj){
- JSONArray jsonObj = null;
- if(obj != null){
- logger.info("后端返回對象:{}", obj);
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
- jsonObj = JSONArray.fromObject(obj, jsonConfig);
- logger.info("后端返回數據:" + jsonObj);
- }
- logger.info("輸出結果:{}", jsonObj.toString());
- return jsonObj.toString();
- }
- /**
- * 返回成功
- * @param obj 輸出對象
- * @return 輸出成功的JSON格式數據
- */
- public String responseSuccess(Object obj, String msg){
- JSONObject jsonObj = null;
- if(obj != null){
- logger.info("后端返回對象:{}", obj);
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
- jsonObj = JSONObject.fromObject(obj, jsonConfig);
- logger.info("后端返回數據:" + jsonObj);
- jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
- jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, msg);
- }
- logger.info("輸出結果:{}", jsonObj.toString());
- return jsonObj.toString();
- }
- /**
- * 返回失敗
- * @param errorMsg 錯誤信息
- * @return 輸出失敗的JSON格式數據
- */
- public String responseFail(String errorMsg){
- JSONObject jsonObj = new JSONObject();
- jsonObj.put(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
- jsonObj.put(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errorMsg);
- logger.info("輸出結果:{}", jsonObj.toString());
- return jsonObj.toString();
- }
- }
上面用到的一些變量如下:
- package com.lin.common;
- public class HttpConstants {
- public static final String SYSTEM_ERROR_MSG = "系統錯誤";
- public static final String REQUEST_PARAMS_NULL = "請求參數為空";
- public static final String SERVICE_RESPONSE_NULL = "服務端返回結果為空";
- // 服務端返回成功的標志
- public static final String SERVICE_RESPONSE_SUCCESS_CODE = "AMS00000";
- // 服務端返回結果的標志
- public static final String SERVICE_RESPONSE_RESULT_FLAG = "returnCode";
- // 服務端返回結果失敗的標志
- public static final String SERVICE_RESPONSE_RESULT_MSG = "errorMsg";
- // 返回給前段頁面成功或失敗的標志
- public static final String RESPONSE_RESULT_FLAG_ISERROR = "isError";
- // 執行刪除操作
- public static final String OPERATION_TYPE_DELETE = "D";
- public static final String ENUM_PATH = "com.mucfc.msm.enumeration.";
- }
引用一個包的內容如下:
- package com.lin.json;
- import net.sf.json.JsonConfig;
- import net.sf.json.processors.JsonValueProcessor;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Locale;
- public class JsonDateValueProcessor implements JsonValueProcessor {
- /**
- * datePattern
- */
- private String datePattern = "yyyy-MM-dd HH:mm:ss";
- /**
- * JsonDateValueProcessor
- */
- public JsonDateValueProcessor() {
- super();
- }
- /**
- * @param format
- */
- public JsonDateValueProcessor(String format) {
- super();
- this.datePattern = format;
- }
- /**
- * @param value
- * @param jsonConfig
- * @return Object
- */
- public Object processArrayValue(Object value, JsonConfig jsonConfig) {
- return process(value);
- }
- /**
- * @param key
- * @param value
- * @param jsonConfig
- * @return Object
- */
- public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
- return process(value);
- }
- /**
- * process
- *
- * @param value
- * @return
- */
- private Object process(Object value) {
- try {
- if (value instanceof Date) {
- SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK);
- return sdf.format((Date) value);
- }
- return value == null ? "" : value.toString();
- } catch (Exception e) {
- return "";
- }
- }
- /**
- * @return the datePattern
- */
- public String getDatePattern() {
- return datePattern;
- }
- /**
- * @param pDatePattern the datePattern to set
- */
- public void setDatePattern(String pDatePattern) {
- datePattern = pDatePattern;
- }
- }
這里主要實現了能將list/map/set/數組等轉換成josn,並傳到前台‘
2、光這里寫不行,還得配置springMVC中以json來傳遞數據,並配置自己的字符過濾器,要不然中文傳到前台可能亂碼,這里的配置比較復雜,大部分時間都花在這里,
這里我直接放spingMVC的配置:spring-mvc.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
- <!-- 掃描controller(controller層注入) -->
- <context:component-scan base-package="com.lin.controller" use-default-filters="false">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
- </context:component-scan>
- <!-- 會自動注冊了validator ConversionService -->
- <mvc:annotation-driven validator="validator" conversion-service="conversionService" content-negotiation-manager="contentNegotiationManager">
- <mvc:message-converters register-defaults="true">
- <!-- StringHttpMessageConverter編碼為UTF-8,防止亂碼 -->
- <bean class="org.springframework.http.converter.StringHttpMessageConverter">
- <constructor-arg value="UTF-8"/>
- <property name = "supportedMediaTypes">
- <list>
- <bean class="org.springframework.http.MediaType">
- <constructor-arg index="0" value="text"/>
- <constructor-arg index="1" value="plain"/>
- <constructor-arg index="2" value="UTF-8"/>
- </bean>
- <bean class="org.springframework.http.MediaType">
- <constructor-arg index="0" value="*"/>
- <constructor-arg index="1" value="*"/>
- <constructor-arg index="2" value="UTF-8"/>
- </bean>
- </list>
- </property>
- </bean>
- <!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
- <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- <!--<property name="serializerFeature">-->
- <!--這個地方加上這個功能吧,能自己配置一些東西,比如時間的格式化,null輸出""等等-->
- <!--</property>-->
- </bean>
- </mvc:message-converters>
- <mvc:argument-resolvers>
- <bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver" />
- </mvc:argument-resolvers>
- </mvc:annotation-driven>
- <!-- 內容協商管理器 -->
- <!--1、首先檢查路徑擴展名(如my.pdf);2、其次檢查Parameter(如my?format=pdf);3、檢查Accept Header-->
- <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
- <!-- 擴展名至mimeType的映射,即 /user.json => application/json -->
- <property name="favorPathExtension" value="true"/>
- <!-- 用於開啟 /userinfo/123?format=json 的支持 -->
- <property name="favorParameter" value="true"/>
- <property name="parameterName" value="format"/>
- <!-- 是否忽略Accept Header -->
- <property name="ignoreAcceptHeader" value="false"/>
- <property name="mediaTypes"> <!--擴展名到MIME的映射;favorPathExtension, favorParameter是true時起作用 -->
- <value>
- json=application/json
- xml=application/xml
- html=text/html
- </value>
- </property>
- <!-- 默認的content type -->
- <property name="defaultContentType" value="text/html"/>
- </bean>
- <!-- 當在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射時,能映射靜態資源 -->
- <mvc:default-servlet-handler />
- <!-- 靜態資源映射 -->
- <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
- <!-- 對模型視圖添加前后綴 -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
- <!-- 這里設置靜態的資源 -->
- <!-- <mvc:resources location="/static/" mapping="/static/**" /> -->
- </beans>
3、Spirng中也和配置:
- <?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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 會 自動注冊-->
- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
- </bean>
- <!-- 引入jdbc配置文件 -->
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:properties/*.properties</value>
- <!--要是有多個配置文件,只需在這里繼續添加即可 -->
- </list>
- </property>
- </bean>
- <!-- 掃描注解Bean -->
- <context:component-scan base-package="com.lin.service">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <!-- 激活annotation功能 -->
- <context:annotation-config />
- <!-- 激活annotation功能 -->
- <context:spring-configured />
- <!-- 注解事務配置 -->
- <!-- 類型轉換及數據格式化 -->
- <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
- <!-- 配置數據源 -->
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <!-- 不使用properties來配置 -->
- <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/learning" />
- <property name="username" value="root" />
- <property name="password" value="christmas258@" /> -->
- <!-- 使用properties來配置 -->
- <property name="driverClassName">
- <value>${jdbc_driverClassName}</value>
- </property>
- <property name="url">
- <value>${jdbc_url}</value>
- </property>
- <property name="username">
- <value>${jdbc_username}</value>
- </property>
- <property name="password">
- <value>${jdbc_password}</value>
- </property>
- </bean>
- <!-- 自動掃描了所有的XxxxMapper.xml對應的mapper接口文件,這樣就不用一個一個手動配置Mpper的映射了,只要Mapper接口類和Mapper映射文件對應起來就可以了。 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage"
- value="com.lin.dao" />
- </bean>
- <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>
- <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
- <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
- /> -->
- </bean>
- </beans>
其中validator這個bean需要引用如下:
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- <version>1.1.0.Final</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>5.0.1.Final</version>
- </dependency>
4、conroller層編寫
- package com.lin.controller;
- import java.util.HashMap;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.data.domain.Pageable;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.servlet.ModelAndView;
- import com.github.pagehelper.Page;
- import com.lin.domain.User;
- import com.lin.service.UserService;
- import com.lin.util.PagedResult;
- /**
- * 功能概要:UserController
- *
- * @author linbingwen
- * @since 2015年9月28日
- */
- @Controller
- public class UserController extends BaseController {
- private Logger logger = LoggerFactory.getLogger(getClass());
- @Resource
- private UserService userService;
- @RequestMapping("/")
- public ModelAndView getIndex(){
- ModelAndView mav = new ModelAndView("index");
- User user = userService.selectUserById(1);
- mav.addObject("user", user);
- return mav;
- }
- /**
- * 顯示首頁
- * @author linbingwen
- * @since 2015年10月23日
- * @return
- */
- @RequestMapping("/bootstrapTest1")
- public String bootStrapTest1(){
- return "bootstrap/bootstrapTest1";
- }
- /**
- * 分頁查詢用戶信息
- * @author linbingwen
- * @since 2015年10月23日
- * @param page
- * @return
- */
- @RequestMapping(value="/list.do", method= RequestMethod.POST)
- @ResponseBody
- public String list(Integer pageNumber,Integer pageSize ,String userName) {
- logger.info("分頁查詢用戶信息列表請求入參:pageNumber{},pageSize{}", pageNumber,pageSize);
- try {
- PagedResult<User> pageResult = userService.queryByPage(userName, pageNumber,pageSize);
- return responseSuccess(pageResult);
- } catch (Exception e) {
- return responseFail(e.getMessage());
- }
- }
- }
5、最后一步就是前台的頁面了,這里可以先寫頁面再來寫controller也可以的
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Bootstrap分頁實例</title>
- <link href="<%=request.getContextPath()%>/static/js/bootstrap//css/bootstrap.min.css" rel="stylesheet">
- <script src="<%=request.getContextPath()%>/static/js/jQuery/jquery-2.1.4.min.js"></script>
- <script src="<%=request.getContextPath()%>/static/js/bootstrap/js/bootstrap.min.js"></script>
- <script src="<%=request.getContextPath()%>/static/js/bootstrap/js/bootstrap-paginator.min.js"></script>
- <style type="text/css">
- #queryDiv {
- margin-right: auto;
- margin-left: auto;
- width:600px;
- }
- #textInput {
- margin-top: 10px;
- }
- #tableResult {
- margin-right: auto;
- margin-left: auto;
- width:600px;
- }
- td {
- width:150px
- }
- </style>
- </head>
- <body>
- <div id = "queryDiv">
- <input id = "textInput" type="text" placeholder="請輸入用戶名" >
- <button id = "queryButton" class="btn btn-primary" type="button">查詢</button>
- </div>
- <form id="form1">
- <table class="table table-bordered" id = 'tableResult'>
- <caption>查詢用戶結果</caption>
- <thead>
- <tr>
- <th>序號</th>
- <th>用戶名</th>
- <th>密碼</th>
- <th>用戶郵箱</th>
- </tr>
- </thead>
- <tbody id="tableBody">
- </tbody>
- </table>
- <!-- 底部分頁按鈕 -->
- <div id="bottomTab"></div>
- </form>
- <script type='text/javascript'>
- var PAGESIZE = 10;
- var options = {
- currentPage: 1, //當前頁數
- totalPages: 10, //總頁數,這里只是暫時的,后頭會根據查出來的條件進行更改
- size:"normal",
- alignment:"center",
- itemTexts: function (type, page, current) {
- switch (type) {
- case "first":
- return "第一頁";
- case "prev":
- return "前一頁";
- case "next":
- return "后一頁";
- case "last":
- return "最后頁";
- case "page":
- return page;
- }
- },
- onPageClicked: function (e, originalEvent, type, page) {
- var userName = $("#textInput").val(); //取內容
- buildTable(userName,page,PAGESIZE);//默認每頁最多10條
- }
- }
- //獲取當前項目的路徑
- var urlRootContext = (function () {
- var strPath = window.document.location.pathname;
- var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
- return postPath;
- })();
- //生成表格
- function buildTable(userName,pageNumber,pageSize) {
- var url = urlRootContext + "/list.do"; //請求的網址
- var reqParams = {'userName':userName, 'pageNumber':pageNumber,'pageSize':pageSize};//請求數據
- $(function () {
- $.ajax({
- type:"POST",
- url:url,
- data:reqParams,
- async:false,
- dataType:"json",
- success: function(data){
- if(data.isError == false) {
- // options.totalPages = data.pages;
- var newoptions = {
- currentPage: 1, //當前頁數
- totalPages: data.pages==0?1:data.pages, //總頁數
- size:"normal",
- alignment:"center",
- itemTexts: function (type, page, current) {
- switch (type) {
- case "first":
- return "第一頁";
- case "prev":
- return "前一頁";
- case "next":
- return "后一頁";
- case "last":
- return "最后頁";
- case "page":
- return page;
- }
- },
- onPageClicked: function (e, originalEvent, type, page) {
- var userName = $("#textInput").val(); //取內容
- buildTable(userName,page,PAGESIZE);//默認每頁最多10條
- }
- }
- $('#bottomTab').bootstrapPaginator("setOptions",newoptions); //重新設置總頁面數目
- var dataList = data.dataList;
- $("#tableBody").empty();//清空表格內容
- if (dataList.length > 0 ) {
- $(dataList).each(function(){//重新生成
- $("#tableBody").append('<tr>');
- $("#tableBody").append('<td>' + this.userId + '</td>');
- $("#tableBody").append('<td>' + this.userName + '</td>');
- $("#tableBody").append('<td>' + this.userPassword + '</td>');
- $("#tableBody").append('<td>' + this.userEmail + '</td>');
- $("#tableBody").append('</tr>');
- });
- } else {
- $("#tableBody").append('<tr><th colspan ="4"><center>查詢無數據</center></th></tr>');
- }
- }else{
- alert(data.errorMsg);
- }
- },
- error: function(e){
- alert("查詢失敗:" + e);
- }
- });
- });
- }
- //渲染完就執行
- $(function() {
- //生成底部分頁欄
- $('#bottomTab').bootstrapPaginator(options);
- buildTable("",1,10);//默認空白查全部
- //創建結算規則
- $("#queryButton").bind("click",function(){
- var userName = $("#textInput").val();
- buildTable(userName,1,PAGESIZE);
- });
- });
- </script>
- </body>
- </html>
注意引入的js文件,bootstrap-paginator需要引用bootstrap和jquery
6、最終運行結果
最后以web工程運行就可以了:
結果如下:

打印出來的一些日志:
后台返回給前台的就是json
http://blog.csdn.net/evankaka/article/details/49452201