前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring+Mybatis+SpringMVC后台与前台分页展示实例(附工程)

Spring+Mybatis+SpringMVC后台与前台分页展示实例(附工程)

作者头像
bear_fish
发布2018-09-20 11:08:18
1K0
发布2018-09-20 11:08:18
举报

      林炳文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包

[html] view plaincopy

  1. <!-- 添加分布插件的包pagehelper -->
  2. <dependency>
  3. <groupId>com.github.pagehelper</groupId>
  4. <artifactId>pagehelper</artifactId>
  5. <version>4.0.0</version>
  6. </dependency>

2.mybatis-config.xml中添加插件

[html] view plaincopy

  1. <plugins>
  2. <!-- com.github.pagehelper为PageHelper类所在包名 -->
  3. <plugin interceptor="com.github.pagehelper.PageHelper">
  4. <property name="dialect" value="mysql"/>
  5. <!-- 该参数默认为false -->
  6. <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
  7. <!-- 和startPage中的pageNum效果一样-->
  8. <property name="offsetAsPageNum" value="true"/>
  9. <!-- 该参数默认为false -->
  10. <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
  11. <property name="rowBoundsWithCount" value="true"/>
  12. <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
  13. <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
  14. <property name="pageSizeZero" value="true"/>
  15. <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
  16. <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
  17. <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
  18. <property name="reasonable" value="false"/>
  19. <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
  20. <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
  21. <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->
  22. <!-- 不理解该含义的前提下,不要随便复制该配置 -->
  23. <property name="params" value="pageNum=start;pageSize=limit;"/>
  24. </plugin>
  25. </plugins>

这样子就引入进来了,接下来就是来开始分页功能的实现

3、mapper文件中添加如下一个方法:

[html] view plaincopy

  1. <select id="selectUserByUserName" parameterType="java.lang.String" resultMap="BaseResultMap">
  2.     SELECT *  
  3.     FROM t_user  
  4.     WHERE 1 = 1
  5. <if test="userName != null and userName !=''">
  6.         AND USER_NAME = #{userName,jdbcType=VARCHAR}  
  7. </if>
  8.     ORDER BY USER_ID  
  9. </select>

注意,这里的返回其实是一个list

[html] view plaincopy

  1. <!--设置domain类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要! -->
  2. <resultMap id="BaseResultMap" type="com.lin.domain.User">
  3. <id column="USER_ID" property="userId" jdbcType="INTEGER" />
  4. <result column="USER_NAME" property="userName" jdbcType="CHAR" />
  5. <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
  6. <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
  7. </resultMap>

4、然后就是dao类

[html] view plaincopy

  1. /**  
  2.  *   
  3.  * @author linbingwen  
  4.  * @since  2015年10月22日   
  5.  * @param userName  
  6.  * @return  
  7.  */  
  8. List<User> selectUserByUserName(@Param("userName") String userName);  

这里一定的记得加@Param("userName")

接下来就可以在service层中添加分页查询的的接口了

5、接口类

[html] view plaincopy

  1. /**  
  2.  *   
  3.  * @author linbingwen  
  4.  * @since  2015年10月23日   
  5.  * @param userName 查询条件,可为空  
  6.  * @param pageNo 查询条件,可为空,默认取1  
  7.  * @param pageSize 查询条件,可为空,默认取10  
  8.  * @return  
  9.  */  
  10. PagedResult<User> queryByPage(String userName,Integer pageNo,Integer pageSize);  

6、实现类

[html] view plaincopy

  1. public PagedResult<User> queryByPage(String userName,Integer pageNo,Integer pageSize ) {  
  2. pageNo = pageNo == null?1:pageNo;  
  3. pageSize = pageSize == null?10:pageSize;  
  4.     PageHelper.startPage(pageNo,pageSize);  //startPage是告诉拦截器说我要开始分页了。分页参数是这两个。  
  5.     return BeanUtil.toPagedResult(userDao.selectUserByUserName(userName));  
  6. }  

这里就可以直接在返回里头使用了PageHelper,这里userDao.selectUserByUserName(userName)的返回是一个list

其中,PagedResult是我自己封装的一个分页结果类

[java] view plaincopy

  1. package com.lin.util;  
  2. import java.util.List;  
  3. import com.lin.dto.BaseEntity;  
  4. /**
  5.  * 功能概要:
  6.  * 
  7.  * @author linbingwen
  8.  * @since  2015年10月23日 
  9.  */
  10. public class PagedResult<T> extends BaseEntity {  
  11. /*serialVersionUID*/
  12. private static final long serialVersionUID = 1L;  
  13. private List<T> dataList;//数据
  14. private long pageNo;//当前页
  15. private long pageSize;//条数
  16. private long total;//总条数
  17. private long pages;//总页面数目
  18. public List<T> getDataList() {  
  19. return dataList;  
  20.     }  
  21. public void setDataList(List<T> dataList) {  
  22. this.dataList = dataList;  
  23.     }  
  24. public long getPageNo() {  
  25. return pageNo;  
  26.     }  
  27. public void setPageNo(long pageNo) {  
  28. this.pageNo = pageNo;  
  29.     }  
  30. public long getPageSize() {  
  31. return pageSize;  
  32.     }  
  33. public void setPageSize(long pageSize) {  
  34. this.pageSize = pageSize;  
  35.     }  
  36. public long getTotal() {  
  37. return total;  
  38.     }  
  39. public void setTotal(long total) {  
  40. this.total = total;  
  41.     }  
  42. public long getPages() {  
  43. return pages;  
  44.     }  
  45. public void setPages(long pages) {  
  46. this.pages = pages;  
  47.     }  
  48. }  

这是它的基类

[html] view plaincopy

  1. package com.lin.dto;  
  2. import java.io.Serializable;  
  3. import java.lang.reflect.Method;  
  4. import java.lang.reflect.Modifier;  
  5. import java.util.ArrayList;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. /**  
  10.  *   
  11.  * <b>类说明:</b>bean基类  
  12.  *   
  13.  * <p>
  14.  * <b>详细描述:</b>
  15.  *   
  16.  * @author costin_law   
  17.  * @since 2014-5-5  
  18.  */  
  19. public abstract class BaseEntity implements Serializable{  
  20.     private static final long serialVersionUID = 1L;  
  21.     private static Map<Class<?>,PropertyInfo[]> class2Props = new HashMap<Class<?>,PropertyInfo[]>(128);  
  22.     @Override  
  23.     public String toString() {  
  24.         PropertyInfo[] props = class2Props.get(this.getClass());  
  25.         if( props == null ){  
  26. props = getProps(this.getClass());  
  27.         }  
  28.         StringBuilder   builder = new StringBuilder(1024);  
  29.         boolean isFirst = true;  
  30.         for (int i = 0, n = props.length; i < n; i++) {  
  31.             try {  
  32.                 PropertyInfo propInfo = props[i];                 
  33.                 Object value = propInfo.getMethod.invoke(this, new Object[0]);  
  34.                 if (isFirst)  
  35. isFirst = false;  
  36.                 else  
  37.                     builder.append(",");  
  38.                 builder.append(propInfo.propName);  
  39.                 builder.append(":");  
  40.                 if (value instanceof String)  
  41.                     builder.append("\"");  
  42.                 builder.append(value);  
  43.                 if (value instanceof String)  
  44.                     builder.append("\"");                 
  45.             } catch (Exception e) {  
  46.                 // ignore  
  47.             }  
  48.         }  
  49.         return "{" + builder.toString() + "}";  
  50.     }  
  51.     private static PropertyInfo[] getProps(Class<? extends BaseEntity> clazz) {  
  52.         PropertyInfo[] props;  
  53.         Method[] allMethods = clazz.getMethods();   
  54.         List<PropertyInfo> propList = new ArrayList<PropertyInfo>();  
  55.         for (int i = 0, n = allMethods.length; i < n; i++) {  
  56.             try {  
  57.                 Method method = allMethods[i];  
  58.                 if ((method.getModifiers() & Modifier.PUBLIC) == 1  
  59.                         && method.getDeclaringClass() != Object.class  
  60.                         && (method.getParameterTypes() == null || method  
  61.                                 .getParameterTypes().length == 0)) {  
  62.                     String methodName = method.getName();  
  63.                     if (methodName.startsWith("get") || methodName.startsWith("is") ) {  
  64.                         PropertyInfo propInfo = new PropertyInfo();                                       
  65. propInfo.getMethod = method;  
  66.                         if (methodName.startsWith("get")) {  
  67. propInfo.propName = methodName.substring(3, 4).toLowerCase()  
  68.                                     + methodName.substring(4);  
  69.                         } else if (methodName.startsWith("is")) {  
  70. propInfo.propName = methodName.substring(2, 3).toLowerCase()  
  71.                                     + methodName.substring(3);  
  72.                         }                 
  73.                         propList.add(propInfo);  
  74.                     }  
  75.                 }                     
  76.             }catch(Exception e){                      
  77.             }  
  78.         }  
  79. props =  new PropertyInfo[propList.size()];  
  80.         propList.toArray(props);  
  81.         class2Props.put(clazz, props);  
  82.         return props;  
  83.     }  
  84.     static class PropertyInfo{  
  85.         Method getMethod;  
  86.         String propName;          
  87.     }  
  88. }  

BeanUtil是一个将PageHelper返回的list转成pageResult的工具

[html] view plaincopy

  1. package com.lin.util;  
  2. import java.util.List;  
  3. import com.github.pagehelper.Page;  
  4. import com.lin.util.PagedResult;  
  5. /**  
  6.  * 功能概要:  
  7.  *   
  8.  * @author linbingwen  
  9.  * @since  2015年10月22日   
  10.  */  
  11. public class BeanUtil {  
  12.     public static <T> PagedResult<T> toPagedResult(List<T> datas) {  
  13.         PagedResult<T> result = new PagedResult<T>();  
  14.         if (datas instanceof Page) {  
  15.             Page page = (Page) datas;  
  16.             result.setPageNo(page.getPageNum());  
  17.             result.setPageSize(page.getPageSize());  
  18.             result.setDataList(page.getResult());  
  19.             result.setTotal(page.getTotal());  
  20.             result.setPages(page.getPages());  
  21.         }  
  22.         else {  
  23.             result.setPageNo(1);  
  24.             result.setPageSize(datas.size());  
  25.             result.setDataList(datas);  
  26.             result.setTotal(datas.size());  
  27.         }  
  28.         return result;  
  29.     }  
  30. }  

7、这样就好了,可以跑单元测试了

[java] view plaincopy

  1. /**
  2.  * 分页测试
  3.  * @author linbingwen
  4.  * @since  2015年10月22日
  5.  */
  6. @Test
  7. public void queryByPage(){  
  8.      PagedResult<User>  pagedResult = userService.queryByPage(null,1,10);//null表示查全部  
  9.      logger.debug("查找结果" + pagedResult);  
  10. }  

输出结果:

看不清的话看下面

查找结果{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包如下:

[html] view plaincopy

  1. <!-- 添加json的依赖包 -->
  2. <dependency>
  3. <groupId>net.sf.json-lib</groupId>
  4. <artifactId>json-lib</artifactId>
  5. <version>2.3</version>
  6. <classifier>jdk15</classifier>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.springframework.data</groupId>
  10. <artifactId>spring-data-commons</artifactId>
  11. <version>1.6.1.RELEASE</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.data</groupId>
  15. <artifactId>spring-data-jpa</artifactId>
  16. <version>1.4.1.RELEASE</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.alibaba</groupId>
  20. <artifactId>fastjson</artifactId>
  21. <version>1.1.34</version>
  22. </dependency>

基类如下:

[java] view plaincopy

  1. package com.lin.controller;  
  2. import com.lin.common.HttpConstants;  
  3. import com.lin.json.JsonDateValueProcessor;  
  4. import net.sf.json.JSONArray;  
  5. import net.sf.json.JSONObject;  
  6. import net.sf.json.JsonConfig;  
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9. import java.util.Date;  
  10. /**
  11.  * Controller基类
  12.  */
  13. public class BaseController {  
  14. protected Logger logger = LoggerFactory.getLogger(this.getClass());  
  15. protected final static String DATE_FORMATE = "yyyy-MM-dd";  
  16. /**
  17.      * 返回服务端处理结果
  18.      * @param obj 服务端输出对象
  19.      * @return 输出处理结果给前段JSON格式数据
  20.      * @author YANGHONGXIA
  21.      * @since 2015-01-06
  22.      */
  23. public String responseResult(Object obj){  
  24.         JSONObject jsonObj = null;  
  25. if(obj != null){  
  26.             logger.info("后端返回对象:{}", obj);  
  27.             JsonConfig jsonConfig = new JsonConfig();   
  28.             jsonConfig.registerJsonValueProcessor(Date.classnew JsonDateValueProcessor());  
  29.             jsonObj = JSONObject.fromObject(obj, jsonConfig);  
  30.             logger.info("后端返回数据:" + jsonObj);  
  31. if(HttpConstants.SERVICE_RESPONSE_SUCCESS_CODE.equals(jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_FLAG))){  
  32.                 jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);  
  33.                 jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");  
  34.             }else{  
  35.                 jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);  
  36.                 String errMsg = jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_MSG);  
  37.                 jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errMsg==null?HttpConstants.SERVICE_RESPONSE_NULL:errMsg);  
  38.             }  
  39.         }  
  40.         logger.info("输出结果:{}", jsonObj.toString());  
  41. return jsonObj.toString();  
  42.     }  
  43. /**
  44.      * 返回成功
  45.      * @param obj 输出对象
  46.      * @return 输出成功的JSON格式数据
  47.      */
  48. public String responseSuccess(Object obj){  
  49.         JSONObject jsonObj = null;  
  50. if(obj != null){  
  51.             logger.info("后端返回对象:{}", obj);  
  52.             JsonConfig jsonConfig = new JsonConfig();   
  53.             jsonConfig.registerJsonValueProcessor(Date.classnew JsonDateValueProcessor());  
  54.             jsonObj = JSONObject.fromObject(obj, jsonConfig);  
  55.             logger.info("后端返回数据:" + jsonObj);  
  56.             jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);  
  57.             jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");  
  58.         }  
  59.         logger.info("输出结果:{}", jsonObj.toString());  
  60. return jsonObj.toString();  
  61.     }  
  62. /**
  63.      * 返回成功
  64.      * @param obj 输出对象
  65.      * @return 输出成功的JSON格式数据
  66.      */
  67. public String responseArraySuccess(Object obj){  
  68.         JSONArray jsonObj = null;  
  69. if(obj != null){  
  70.             logger.info("后端返回对象:{}", obj);  
  71.             JsonConfig jsonConfig = new JsonConfig();  
  72.             jsonConfig.registerJsonValueProcessor(Date.classnew JsonDateValueProcessor());  
  73.             jsonObj = JSONArray.fromObject(obj, jsonConfig);  
  74.             logger.info("后端返回数据:" + jsonObj);  
  75.         }  
  76.         logger.info("输出结果:{}", jsonObj.toString());  
  77. return jsonObj.toString();  
  78.     }  
  79. /**
  80.      * 返回成功
  81.      * @param obj 输出对象
  82.      * @return 输出成功的JSON格式数据
  83.      */
  84. public String responseSuccess(Object obj, String msg){  
  85.         JSONObject jsonObj = null;  
  86. if(obj != null){  
  87.             logger.info("后端返回对象:{}", obj);  
  88.             JsonConfig jsonConfig = new JsonConfig();   
  89.             jsonConfig.registerJsonValueProcessor(Date.classnew JsonDateValueProcessor());  
  90.             jsonObj = JSONObject.fromObject(obj, jsonConfig);  
  91.             logger.info("后端返回数据:" + jsonObj);  
  92.             jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);  
  93.             jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, msg);  
  94.         }  
  95.         logger.info("输出结果:{}", jsonObj.toString());  
  96. return jsonObj.toString();  
  97.     }  
  98. /**
  99.      * 返回失败
  100.      * @param errorMsg 错误信息
  101.      * @return 输出失败的JSON格式数据
  102.      */
  103. public String responseFail(String errorMsg){  
  104.         JSONObject jsonObj = new JSONObject();  
  105.         jsonObj.put(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);  
  106.         jsonObj.put(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errorMsg);  
  107.         logger.info("输出结果:{}", jsonObj.toString());  
  108. return jsonObj.toString();  
  109.     }  
  110. }  

上面用到的一些变量如下:

[java] view plaincopy

  1. package com.lin.common;  
  2. public class HttpConstants {  
  3. public static final String SYSTEM_ERROR_MSG = "系统错误";  
  4. public static final String REQUEST_PARAMS_NULL = "请求参数为空";  
  5. public static final String SERVICE_RESPONSE_NULL = "服务端返回结果为空";  
  6. // 服务端返回成功的标志
  7. public static final String SERVICE_RESPONSE_SUCCESS_CODE = "AMS00000";  
  8. // 服务端返回结果的标志
  9. public static final String SERVICE_RESPONSE_RESULT_FLAG = "returnCode";  
  10. // 服务端返回结果失败的标志
  11. public static final String SERVICE_RESPONSE_RESULT_MSG = "errorMsg";  
  12. // 返回给前段页面成功或失败的标志
  13. public static final String RESPONSE_RESULT_FLAG_ISERROR = "isError";  
  14. // 执行删除操作
  15. public static final String OPERATION_TYPE_DELETE = "D";  
  16. public static final String ENUM_PATH = "com.mucfc.msm.enumeration.";  
  17. }  

引用一个包的内容如下:

[java] view plaincopy

  1. package com.lin.json;  
  2. import net.sf.json.JsonConfig;  
  3. import net.sf.json.processors.JsonValueProcessor;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6. import java.util.Locale;  
  7. public class JsonDateValueProcessor implements JsonValueProcessor {  
  8. /**
  9.      * datePattern
  10.      */
  11. private String datePattern = "yyyy-MM-dd HH:mm:ss";  
  12. /**
  13.      * JsonDateValueProcessor
  14.      */
  15. public JsonDateValueProcessor() {  
  16. super();  
  17.     }  
  18. /**
  19.      * @param format
  20.      */
  21. public JsonDateValueProcessor(String format) {  
  22. super();  
  23. this.datePattern = format;  
  24.     }  
  25. /**
  26.      * @param value
  27.      * @param jsonConfig
  28.      * @return Object
  29.      */
  30. public Object processArrayValue(Object value, JsonConfig jsonConfig) {  
  31. return process(value);  
  32.     }  
  33. /**
  34.      * @param key
  35.      * @param value
  36.      * @param jsonConfig
  37.      * @return Object
  38.      */
  39. public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {  
  40. return process(value);  
  41.     }  
  42. /**
  43.      * process
  44.      *
  45.      * @param value
  46.      * @return
  47.      */
  48. private Object process(Object value) {  
  49. try {  
  50. if (value instanceof Date) {  
  51.                 SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK);  
  52. return sdf.format((Date) value);  
  53.             }  
  54. return value == null ? "" : value.toString();  
  55.         } catch (Exception e) {  
  56. return "";  
  57.         }  
  58.     }  
  59. /**
  60.      * @return the datePattern
  61.      */
  62. public String getDatePattern() {  
  63. return datePattern;  
  64.     }  
  65. /**
  66.      * @param pDatePattern the datePattern to set
  67.      */
  68. public void setDatePattern(String pDatePattern) {  
  69.         datePattern = pDatePattern;  
  70.     }  
  71. }  

这里主要实现了能将list/map/set/数组等转换成josn,并传到前台‘

2、光这里写不行,还得配置springMVC中以json来传递数据,并配置自己的字符过滤器,要不然中文传到前台可能乱码,这里的配置比较复杂,大部分时间都花在这里,

这里我直接放spingMVC的配置:spring-mvc.xml

[html] view plaincopy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="  
  8.     http://www.springframework.org/schema/beans  
  9.     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  10.     http://www.springframework.org/schema/context  
  11.     http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  12.     http://www.springframework.org/schema/mvc  
  13.     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  14. <!-- 扫描controller(controller层注入) -->
  15. <context:component-scan base-package="com.lin.controller" use-default-filters="false">
  16. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  17. <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
  18. </context:component-scan>
  19. <!-- 会自动注册了validator  ConversionService  -->
  20. <mvc:annotation-driven validator="validator" conversion-service="conversionService" content-negotiation-manager="contentNegotiationManager">
  21. <mvc:message-converters register-defaults="true">
  22. <!-- StringHttpMessageConverter编码为UTF-8,防止乱码 -->
  23. <bean class="org.springframework.http.converter.StringHttpMessageConverter">
  24. <constructor-arg value="UTF-8"/>
  25. <property name = "supportedMediaTypes">
  26. <list>
  27. <bean class="org.springframework.http.MediaType">
  28. <constructor-arg index="0" value="text"/>
  29. <constructor-arg index="1" value="plain"/>
  30. <constructor-arg index="2" value="UTF-8"/>
  31. </bean>
  32. <bean class="org.springframework.http.MediaType">
  33. <constructor-arg index="0" value="*"/>
  34. <constructor-arg index="1" value="*"/>
  35. <constructor-arg index="2" value="UTF-8"/>
  36. </bean>
  37. </list>
  38. </property>
  39. </bean>
  40. <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
  41. <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  42. <property name="supportedMediaTypes">
  43. <list>
  44. <value>application/json;charset=UTF-8</value>
  45. </list>
  46. </property>
  47. <!--<property name="serializerFeature">-->
  48. <!--这个地方加上这个功能吧,能自己配置一些东西,比如时间的格式化,null输出""等等-->
  49. <!--</property>-->
  50. </bean>
  51. </mvc:message-converters>
  52. <mvc:argument-resolvers>
  53. <bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver" />
  54. </mvc:argument-resolvers>
  55. </mvc:annotation-driven>
  56. <!-- 内容协商管理器  -->
  57. <!--1、首先检查路径扩展名(如my.pdf);2、其次检查Parameter(如my?format=pdf);3、检查Accept Header-->
  58. <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
  59. <!-- 扩展名至mimeType的映射,即 /user.json => application/json -->
  60. <property name="favorPathExtension" value="true"/>
  61. <!-- 用于开启 /userinfo/123?format=json 的支持 -->
  62. <property name="favorParameter" value="true"/>
  63. <property name="parameterName" value="format"/>
  64. <!-- 是否忽略Accept Header -->
  65. <property name="ignoreAcceptHeader" value="false"/>
  66. <property name="mediaTypes"> <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用  -->
  67. <value>
  68. json=application/json  
  69. xml=application/xml  
  70. html=text/html  
  71. </value>
  72. </property>
  73. <!-- 默认的content type -->
  74. <property name="defaultContentType" value="text/html"/>
  75. </bean>
  76. <!-- 当在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
  77. <mvc:default-servlet-handler />
  78. <!-- 静态资源映射 -->
  79. <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
  80. <!-- 对模型视图添加前后缀 -->
  81. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  82. p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
  83. <!-- 这里设置静态的资源 -->
  84. <!--     <mvc:resources location="/static/" mapping="/static/**" /> -->
  85. </beans>

3、Spirng中也和配置:

[html] view plaincopy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="    
  6.            http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  8.            http://www.springframework.org/schema/aop    
  9.            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.            http://www.springframework.org/schema/context    
  11.            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  12. <!-- 以下 validator  ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
  13. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  14. </bean>
  15. <!-- 引入jdbc配置文件 -->
  16. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  17. <property name="locations">
  18. <list>
  19. <value>classpath:properties/*.properties</value>
  20. <!--要是有多个配置文件,只需在这里继续添加即可 -->
  21. </list>
  22. </property>
  23. </bean>
  24. <!-- 扫描注解Bean -->
  25. <context:component-scan base-package="com.lin.service">
  26. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  27. </context:component-scan>
  28. <!-- 激活annotation功能 -->
  29. <context:annotation-config />
  30. <!-- 激活annotation功能 -->
  31. <context:spring-configured />
  32. <!-- 注解事务配置 -->
  33. <!-- 类型转换及数据格式化 -->
  34. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
  35. <!-- 配置数据源 -->
  36. <bean id="dataSource"
  37. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  38. <!-- 不使用properties来配置 -->
  39.         <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  40. <property name="url" value="jdbc:mysql://localhost:3306/learning" />
  41. <property name="username" value="root" />
  42. <property name="password" value="christmas258@" /> -->
  43. <!-- 使用properties来配置 -->
  44. <property name="driverClassName">
  45. <value>${jdbc_driverClassName}</value>
  46. </property>
  47. <property name="url">
  48. <value>${jdbc_url}</value>
  49. </property>
  50. <property name="username">
  51. <value>${jdbc_username}</value>
  52. </property>
  53. <property name="password">
  54. <value>${jdbc_password}</value>
  55. </property>
  56. </bean>
  57. <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
  58. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  59. <property name="basePackage"
  60. value="com.lin.dao" />
  61. </bean>
  62. <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
  63. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  64. <property name="dataSource" ref="dataSource" />
  65. <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>
  66. <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
  67.         <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
  68. /> -->
  69. </bean>
  70. </beans>

其中validator这个bean需要引用如下:

[html] view plaincopy

  1. <dependency>
  2. <groupId>javax.validation</groupId>
  3. <artifactId>validation-api</artifactId>
  4. <version>1.1.0.Final</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.hibernate</groupId>
  8. <artifactId>hibernate-validator</artifactId>
  9. <version>5.0.1.Final</version>
  10. </dependency>

4、conroller层编写

[java] view plaincopy

  1. package com.lin.controller;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import javax.annotation.Resource;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.data.domain.Pageable;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.ResponseBody;  
  12. import org.springframework.web.servlet.ModelAndView;  
  13. import com.github.pagehelper.Page;  
  14. import com.lin.domain.User;  
  15. import com.lin.service.UserService;  
  16. import com.lin.util.PagedResult;  
  17. /**
  18.  * 功能概要:UserController
  19.  * 
  20.  * @author linbingwen
  21.  * @since  2015年9月28日 
  22.  */
  23. @Controller
  24. public class UserController extends BaseController {  
  25. private Logger logger = LoggerFactory.getLogger(getClass());  
  26. @Resource
  27. private UserService userService;  
  28. @RequestMapping("/")    
  29. public ModelAndView getIndex(){      
  30.         ModelAndView mav = new ModelAndView("index");   
  31.         User user = userService.selectUserById(1);  
  32.         mav.addObject("user", user);   
  33. return mav;    
  34.     }    
  35. /**
  36.      * 显示首页
  37.      * @author linbingwen
  38.      * @since  2015年10月23日 
  39.      * @return
  40.      */
  41. @RequestMapping("/bootstrapTest1")    
  42. public String bootStrapTest1(){  
  43. return "bootstrap/bootstrapTest1";  
  44.     }  
  45. /**
  46.      * 分页查询用户信息
  47.      * @author linbingwen
  48.      * @since  2015年10月23日 
  49.      * @param page
  50.      * @return
  51.      */
  52. @RequestMapping(value="/list.do", method= RequestMethod.POST)  
  53. @ResponseBody
  54. public String list(Integer pageNumber,Integer pageSize ,String userName) {  
  55.         logger.info("分页查询用户信息列表请求入参:pageNumber{},pageSize{}", pageNumber,pageSize);  
  56. try {  
  57.             PagedResult<User> pageResult = userService.queryByPage(userName, pageNumber,pageSize);  
  58. return responseSuccess(pageResult);  
  59.         } catch (Exception e) {  
  60. return responseFail(e.getMessage());  
  61.         }  
  62.     }  
  63. }  

5、最后一步就是前台的页面了,这里可以先写页面再来写controller也可以的

[html] view plaincopy

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Bootstrap分页实例</title>
  8. <link href="<%=request.getContextPath()%>/static/js/bootstrap//css/bootstrap.min.css" rel="stylesheet">
  9. <script src="<%=request.getContextPath()%>/static/js/jQuery/jquery-2.1.4.min.js"></script>
  10. <script src="<%=request.getContextPath()%>/static/js/bootstrap/js/bootstrap.min.js"></script>
  11. <script src="<%=request.getContextPath()%>/static/js/bootstrap/js/bootstrap-paginator.min.js"></script>
  12. <style type="text/css">
  13. #queryDiv {  
  14.  margin-right: auto;  
  15.  margin-left: auto;  
  16.  width:600px;  
  17. }  
  18. #textInput {  
  19.  margin-top: 10px;  
  20. }  
  21. #tableResult {  
  22.  margin-right: auto;  
  23.  margin-left: auto;  
  24.  width:600px;  
  25. }  
  26. td {  
  27.  width:150px  
  28. }  
  29. </style>
  30. </head>
  31. <body>
  32. <div id = "queryDiv">
  33. <input id = "textInput" type="text" placeholder="请输入用户名" >
  34. <button id = "queryButton" class="btn btn-primary" type="button">查询</button>
  35. </div>
  36. <form id="form1">
  37. <table class="table table-bordered" id = 'tableResult'>
  38. <caption>查询用户结果</caption>
  39. <thead>
  40. <tr>
  41. <th>序号</th>
  42. <th>用户名</th>
  43. <th>密码</th>
  44. <th>用户邮箱</th>
  45. </tr>
  46. </thead>
  47. <tbody id="tableBody">
  48. </tbody>
  49. </table>
  50. <!-- 底部分页按钮 -->
  51. <div id="bottomTab"></div>
  52. </form>
  53. <script type='text/javascript'>
  54.         var PAGESIZE = 10;  
  55.         var options = {    
  56.             currentPage: 1,  //当前页数  
  57.             totalPages: 10,  //总页数,这里只是暂时的,后头会根据查出来的条件进行更改  
  58.             size:"normal",    
  59.             alignment:"center",    
  60.             itemTexts: function (type, page, current) {    
  61.                 switch (type) {    
  62.                     case "first":    
  63.                         return "第一页";    
  64.                     case "prev":    
  65.                         return "前一页";    
  66.                     case "next":    
  67.                         return "后一页";    
  68.                     case "last":    
  69.                         return "最后页";    
  70.                     case "page":    
  71.                         return  page;    
  72.                 }                   
  73.             },    
  74.             onPageClicked: function (e, originalEvent, type, page) {    
  75.                 var userName = $("#textInput").val(); //取内容  
  76.                 buildTable(userName,page,PAGESIZE);//默认每页最多10条  
  77.             }    
  78.         }    
  79.         //获取当前项目的路径  
  80.         var urlRootContext = (function () {  
  81.             var strPath = window.document.location.pathname;  
  82.             var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);  
  83.             return postPath;  
  84.         })();  
  85.         //生成表格  
  86.         function buildTable(userName,pageNumber,pageSize) {  
  87.              var url =  urlRootContext + "/list.do"; //请求的网址  
  88.              var reqParams = {'userName':userName, 'pageNumber':pageNumber,'pageSize':pageSize};//请求数据  
  89.              $(function () {     
  90.                   $.ajax({  
  91.                         type:"POST",  
  92.                         url:url,  
  93.                         data:reqParams,  
  94.                         async:false,  
  95.                         dataType:"json",  
  96.                         success: function(data){  
  97.                             if(data.isError == false) {  
  98.                            // options.totalPages = data.pages;  
  99.                         var newoptions = {    
  100.                         currentPage: 1,  //当前页数  
  101.                         totalPages: data.pages==0?1:data.pages,  //总页数  
  102.                         size:"normal",    
  103.                         alignment:"center",    
  104.                         itemTexts: function (type, page, current) {    
  105.                         switch (type) {    
  106.                             case "first":    
  107.                             return "第一页";    
  108.                             case "prev":    
  109.                             return "前一页";    
  110.                             case "next":    
  111.                             return "后一页";    
  112.                             case "last":    
  113.                             return "最后页";    
  114.                         case "page":    
  115.                         return  page;    
  116.                 }                   
  117.             },    
  118.             onPageClicked: function (e, originalEvent, type, page) {    
  119.                 var userName = $("#textInput").val(); //取内容  
  120.                 buildTable(userName,page,PAGESIZE);//默认每页最多10条  
  121.             }    
  122.          }                           
  123.          $('#bottomTab').bootstrapPaginator("setOptions",newoptions); //重新设置总页面数目  
  124.          var dataList = data.dataList;  
  125.          $("#tableBody").empty();//清空表格内容  
  126.          if (dataList.length > 0 ) {  
  127.              $(dataList).each(function(){//重新生成  
  128.                     $("#tableBody").append('<tr>');  
  129.                     $("#tableBody").append('<td>' + this.userId + '</td>');  
  130.                     $("#tableBody").append('<td>' + this.userName + '</td>');  
  131.                     $("#tableBody").append('<td>' + this.userPassword + '</td>');  
  132.                     $("#tableBody").append('<td>' + this.userEmail + '</td>');  
  133.                     $("#tableBody").append('</tr>');  
  134.                     });    
  135.                     } else {                                  
  136.                           $("#tableBody").append('<tr><th colspan ="4"><center>查询无数据</center></th></tr>');  
  137.                     }  
  138.                     }else{  
  139.                           alert(data.errorMsg);  
  140.                             }  
  141.                       },  
  142.                         error: function(e){  
  143.                            alert("查询失败:" + e);  
  144.                         }  
  145.                     });  
  146.                });  
  147.         }  
  148.         //渲染完就执行  
  149.         $(function() {  
  150.             //生成底部分页栏  
  151.             $('#bottomTab').bootstrapPaginator(options);       
  152.             buildTable("",1,10);//默认空白查全部  
  153.             //创建结算规则  
  154.             $("#queryButton").bind("click",function(){  
  155.                 var userName = $("#textInput").val();     
  156.                 buildTable(userName,1,PAGESIZE);  
  157.             });  
  158.         });  
  159. </script>
  160. </body>
  161. </html>

注意引入的js文件,bootstrap-paginator需要引用bootstrap和jquery

6、最终运行结果

最后以web工程运行就可以了:

结果如下:

打印出来的一些日志:

后台返回给前台的就是json

整个工程下载

版权声明:本文为博主林炳文Evankaka原创文章,转载请注明出处http://blog.csdn.net/evankaka

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年11月01日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、后台PageHelper使用
  • 二、前台展示分页结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档