SpringMVC -jquery实现分页

效果图:

关键类的代码:

package:utils:

SpringUtil.java

通过jdbcTemplate连接oracle数据库

package com.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author lyx
 *
 * 2015-8-18下午3:53:19
 *
 *com.utils.SpringUtil
 *	TODO
 */
public class SpringUtil {

	private static ApplicationContext ctx =new ClassPathXmlApplicationContext("springmvc-servlet.xml");

	public static Object getBean(String beanId)
	{
		return ctx.getBean(beanId);
	}
}

ResultUtil.java

实现页面和控制层传递数据的交互类

package com.utils;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

/**
 * @author lyx
 *
 * 2015-8-18下午1:39:40
 *
 *com.yr.utils.ResultUtil
 *	TODO 结果工具类
 */
public class ResultUtil {

		/**
		 * 保存json对象
		 */
		private Map<String,Object> results;

		//---- key值:		

		private static final String MSG="msg";
		private static final String SUCCESS="success";
		/**
		 * 单独对象
		 */
		private static final String OBJ ="obj";
		/**
		 * 列表对象
		 */
		private static final String ROWS="rows";

		private static final String TOTAL ="total";

		private static final String STATUS="status";

		private static final String SIZE="size";

		/**
		 *构造函数初始化
		 */
		public ResultUtil() {
			this.results = new HashMap<String,Object>();
			//默认值
			this.results.put(SUCCESS, true);
		}

		public Map<String, Object> getResult() {
			return results;
		}

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

		public  String getMsg() {
			return (String) results.get(MSG);
		}

		public  boolean getSuccess() {
			return (Boolean) results.get(SUCCESS);
		}

		public  String getObj() {
			return OBJ;
		}

		public  void setRows(Object rows) {
			 this.results.put(ROWS,rows);
		}

		public  void setTotal(Integer total) {
			this.results.put(TOTAL, total);
		}

		public  void setSize(Integer szie) {
			this.results.put(SIZE, szie);
		}

		/**
		 * @param key
		 * @param value
		 * 自定义添加属性标识
		 */
		public void setProperty(String key,Object value)
		{
			try {
				this.results.put(key, value);
			} catch (Exception e) {
				// TODO: handle exception
				//logger.error("出错时:key:"+key+",value:"+value+",Json时错误是:",e);
			}
		}

		public void setStatus(String status)
		{
			setProperty(STATUS, status);
		}

		public void setSuccess(boolean success)
		{
			setProperty(SUCCESS, success);
		}

		public void setMsg(String Msg)
		{
			setProperty(MSG, Msg);
		}

		public void setTotal(int size)
		{
			setProperty(TOTAL, size);
		}

		public void setSize(int size)
		{
			setProperty(SIZE, size);
		}

		public void setData(String data)
		{
			setProperty(ROWS, data);
		}

		public void setObj(Object obj)
		{
			setProperty(OBJ, obj);
		}

		public String toJsonString()
		{
			JSONObject obj =new JSONObject();
			obj.put("data", this.results);
			return obj.toString();
		}

		public static void main(String[] args)
		{
			ResultUtil utils =new ResultUtil();
			System.out.println(utils.toJsonString());
		}

}

UserDaoImpl.java

方法的实现类

package com.dao.Impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import com.dao.UserDao;
import com.utils.SpringUtil;

public class UserDaoImpl implements UserDao {

	private JdbcTemplate jdbc =(JdbcTemplate) SpringUtil.getBean("jdbcTemplate");

	public List<Map<String,Object>> queryAllInfo(int currentPage,int limitPage) {
		// TODO Auto-generated method stub

		String sql="SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select * from LYX.MEMBERUSER m order by m.memberid Asc) A WHERE ROWNUM <="+(currentPage*limitPage)+")WHERE RN >"+((currentPage-1)*limitPage)+"";

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

		list = jdbc.queryForList(sql);

		return list;
	}

	public int totalCount() {

		String sql="select count(*) from LYX.MEMBERUSER";

		return jdbc.queryForInt(sql);
	}

}

UserController.java

控制层

package com.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.utils.ResultUtil;

import service.impl.UserServiceImpl;

/**
 * @author lyx
 *
 * 2015-8-19上午8:53:52
 *
 *com.controller.UserController
 *	TODO
 */
@Controller
@RequestMapping("/user")
public class UserController {

	 private UserServiceImpl service; 

	@RequestMapping("/queryAllInfo")
	@ResponseBody
	public Map<String,Object> queryAllInfo(HttpServletRequest request,HttpServletResponse response)
	{
		service = new UserServiceImpl();

		ResultUtil result =new ResultUtil();

		//数据库总的数据总条数
		int totalRecords =service.totalCount();
		//当前页
		int currentPage=1;
		//每页多少条数据
		int limitPage=5;

		//获得当前页 和 每页条数
		if(request.getParameter("currentPage")!=null)
			currentPage=Integer.valueOf(request.getParameter("currentPage"));
		if(request.getParameter("limitPage")!=null)
			limitPage =Integer.valueOf(request.getParameter("limitPage"));

		//总页数
		int totalpage;
		if(totalRecords<=limitPage)
		{
			totalpage=1;
		}else if((totalRecords%limitPage)==0)
		{
			totalpage=totalRecords/limitPage;
		}else
		{
			totalpage=(totalRecords/limitPage)+1;
		}

		 //根据当前页和每页条数获取结果集
		List<Map<String,Object>> list = service.queryAllInfo(currentPage,limitPage);

		if(list.size()>0)
		{
			//数据集
			result.setRows(list);
			//总页数
			result.setTotal(totalpage);
			//总记录数
			result.setSize(totalRecords);
			result.setMsg("查询成功!");
		}else
		{
			result.setSuccess(false);
			result.setMsg("查询失败!");
		}

		return result.getResult();
	}

}

springmvc-servlet.xml

springmvc配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <!-- springMVC比较详细注解 -->

  <!-- 基本配置  -begin-->

      <!-- 自动注入 -->
      <context:annotation-config></context:annotation-config>
      <!-- 自动扫描包  组件扫描-->
      <context:component-scan base-package="com"></context:component-scan>

      <!-- 注释驱动 -->
      <mvc:annotation-driven/>

      <!-- 配置不用DispatcherServlet 拦截的路径 -->
      <mvc:resources location="/res/" mapping="/res/**"/>
      <!-- 默认分发处理器不会拦截静态资源 -->
     <!--  <mvc:default-servlet-handler/> -->

      <!-- 默认地址栏访问跳转到首页 -->
   <!--   <mvc:view-controller path="/" view-name="forward:/index"/>  -->
      <!-- 也可以利用<mvc:view-controller/>配置错误页面的跳转 -->

      <!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 -->
     <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      	<property name="messageConverters">
      		<list>
      			<!-- 解析JSON数据,将json转换成java对象
      			避免IE执行AJAX时,返回JSON出现下载文件 -->
      			<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
      				<property name="supportedMediaTypes">
      					<list>
      						<value>text/html;charset=UTF-8</value>
      					</list>
      				</property>
      			</bean>

      		</list>
      	</property>
      </bean> 

        <!-- 配置多请求数据类型,如json xml -->
  <!--   <bean id="annotationMethodHandlerAdapter"
          class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                解析json请求数据,将json转换为java对象
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                可以增加其他数据类型,参考spring的API
            </list>
        </property>
    </bean>
       -->

      <!-- 视图解析器 -->
 	   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
		 <property name="prefix" value="/"></property>
		 <property name="suffix" value=".jsp"></property>
	  </bean> 

	<!-- 基本配置  -end-->

	<!-- 功能配置 -begin-->

		<!-- 引入项目配置文件 -->
		<!-- 配置springJDBC Template -->
	 	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
			<property name="locations">
				<list>
					<value>classpath:dbconfig.properties</value>
				</list>
			</property>
		</bean> 

		 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
				<property name="url" value="${url}"></property>
				<property name="driverClassName"  value="${driverClassName}"></property>
				<property name="username" value="${username}"></property>
				<property name="password" value="${password}"></property>
			</bean>
				<!-- jdbcTemplate -->
			<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
				<property name="dataSource" ref="dataSource">

				</property>
			</bean> 

	     <!-- 文件上传配置 -->
	  <!--    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	     	<property name="defaultEncoding" value="UTF-8"></property> 默认编码
	     	<property name="maxUploadSize" value="10000000"></property> 上传文件大小
	     </bean> -->

	      <!-- 拦截器 -->
	      <!--
		<mvc:interceptors>
			 <mvc:interceptor>
			 	拦截全部地址
				<mvc:mapping path="/**"/>
				登录拦截类
				<bean id="loginInterceptor" class="com.sgcc.uds.fs.config.web.interceptor.LoginInterceptor">
				</bean>
			 </mvc:interceptor>
		</mvc:interceptors>
		-->

		<!-- 异常 -->
		<!--
		  <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	      <property name="exceptionMappings">
	        <props>
	        	登录失败异常类
	          <prop key="com.sgcc.uds.fs.config.web.interceptor.UnLoginException">redirect:/toLogin</prop>
	        </props>
	      </property>
	    </bean>
	    -->

   <!-- 功能配置 -end-->

</beans>

index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("home", path);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<link rel="stylesheet" href="${home}/res/css/bootstrap.min.css" type="text/css"></link>
	<link rel="stylesheet" href="${home}/res/css/allStyle.css" type="text/css"></link>

	<style type="text/css">

	.userTable{

		font-size: 20px;
	}

	</style>

	<script type="text/javascript">
		var home ="${home}";
	</script>
  </head>

  <body>

   <h2 class="sub-header">用户列表</h2> 

	<!--  <div class="addbtn" >
	<button class="btn  btn-warning" data-toggle="modal"
			data-target="#addModal">增加用户</button>
	</div>  -->

	<!-- 信息列表 -->
	<div class="table-responsive">
	<!--  -->
		<table class="userTable table table-striped table-bordered table-hover" id="userListTable">
			<thead>
				<tr>
					<th>MEMBERNAME</th>
		   			<th>ACCOUNTNUMBER</th>
		   			<th>AGE</th>
		   			<th>GENDER</th>
		   			<th>BIRTHDAY</th>
		   			<th>MEMBER_LABEL</th>
				</tr>
			</thead>
			<tbody>

			</tbody>

		</table>

		<!-- 分页 -->
		 <ul id="pages" class="pages"></ul>

		共 <input type="text" id="pageSize" value="5" readonly="readonly"> 条记录 /当前页:<input type="text" id="currentPage" readonly="readonly" class="currentPage">
	</div>

    <script type="text/javascript" src="${home}/res/js/jquery-1.11.3.min.js"></script>
	<script type="text/javascript" src="${home}/res/js/bootstrap.min.js"></script>
	<%-- <script type="text/javascript" src="${home}/res/js/jquery.1.7.2.min.js"></script> --%>
	<script type="text/javascript" src="${home}/res/js/docs.min.js"></script>
	<script type="text/javascript"
		src="${home}/res/js/ie10-viewport-bug-workaround.js"></script>
	<script type="text/javascript" src="${home}/res/js/memberUser.js"></script>

	<!-- 分页  -->
	<script src="${home}/res/js/page/jquery.twbsPagination.js" type="text/javascript"></script>
	<%-- <script src="${home}/js/page/zzsc.js" type="text/javascript"></script> --%>
  </body>
</html>

memberUser.js

//加载数据
  	$(document).ready(function() {

		var param={};
		param.currentPage=1;
		param.limitPage=2;

		$.post(home+"/user/queryAllInfo",null,
			function(result)
			{
				if(result !=null && result.success)
					{
						var obj =result.rows;

						//总的页数是否大于10 如果大于则显示10页,否则显示总的页数
						var visiblePage=result.total>10?10:result.total;

						for ( var i = 0; i < obj.length; i++) {

							var user =obj[i];

							var tr = "<tr><td>"
								+ user.MEMBERNAME
								+ " </td>  <td>"
								+ user.ACCOUNTNUMBER
								+ " </td>  <td>"
								+ user.AGE
								+ " </td>  <td>"
								+ user.GENDER
								+ " </td>  <td>"
								+ user.BIRTHDAY
								+ " </td>  <td>"
								+ user.MEMBER_LABEL
								+ " </td>";

							$(".userTable").append(tr);

							//--------------分页
							 $('#pages').twbsPagination({
								 //总共多少页
							        totalPages: result.total,
							     //页面显示几页
							        visiblePages:visiblePage,
							        version: '1.1',
							       // href:home + "/user/queryAllInfo",
							        onPageClick: function (event, page) {
							        	//调用分页函数
							        	setPage(page);
							        }
							    });
						}

					}else
						{
						alert(result.msg);
						}

		},"json"
		);

	});  

  	//实现分页
  	function setPage(currentPage)
  	{
  		var param={};
		param.currentPage=currentPage;
		//每页几条数据
		param.limitPage=5;

		$.post(home+"/user/queryAllInfo",param,
			function(result)
			{
				if(result !=null && result.success)
					{

						var obj =result.rows;

						$("#pageSize").val(result.size);

						//清空上一次查询表中数据
						$('.userTable tbody').empty();

						for ( var i = 0; i < obj.length; i++) {

							var user =obj[i];

							var tr = "<tr><td>"
								+ user.MEMBERNAME
								+ " </td>  <td>"
								+ user.ACCOUNTNUMBER
								+ " </td>  <td>"
								+ user.AGE
								+ " </td>  <td>"
								+ user.GENDER
								+ " </td>  <td>"
								+ user.BIRTHDAY
								+ " </td>  <td>"
								+ user.MEMBER_LABEL
								+ " </td>";

							$(".userTable").append(tr);

						}

					}else
						{
						alert(result.msg);
						}

		},"json"
		);

  	}

项目源码:http://download.csdn.net/detail/u013147600/9024027

四种jQuery+bootstrap分页效果插件: http://download.csdn.net/detail/u013147600/9023943

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-09-29 22:25:23

SpringMVC -jquery实现分页的相关文章

jQuery实现分页

转载地址 http://www.cnblogs.com/xiaoruoen/archive/2012/01/11/2318199.html ;( function($){ $.extend({ "easypage":function(options){ options = $.extend({//参数设置 contentclass:"contentlist",//要显示的内容的class navigateid:"navigatediv",//导航

jquery 3D分页翻转滑块

jquery 3D分页翻转滑块,jquery分页,jquery插件,jquery,3D翻转,css3分页,360度旋转,网页特效代码3D分页翻转滑块是一款使用网格样式与滑块效果分页的特效. jquery 3D分页翻转滑块,布布扣,bubuko.com

jquery ajax分页插件特效源代码demo完整版

原文:jquery ajax分页插件特效源代码demo完整版 源代码下载地址:http://www.zuidaima.com/share/1550463586798592.htm 网上找的,原版本没有测试数据和建表脚本啥的,我给加上了.

jQuery Pagination分页插件

jQuery Pagination分页插件 1.介绍 此jQuery插件为Ajax分页插件,一次性加载,故分页切换时无刷新与延迟. 2.使用方法 1.引入以下的js和css文件 1 <link rel="stylesheet" href="pagination.css"> 2 <script type="text/javascript" src="jquery.min.js"></script&g

jquery动态分页

最近一直研究jquery的分页效果,刚刚弄好了一个,拿出来与大家分享.分页效果与时光网的差不多. 网址:http://www.mtime.com/movie/news/all/ 先在aspx页面放置一个<div class="pageDivs"></div> ,这个是用来存放分页的. 然后建一个page.js文件,具体代码如下(js中用到的css类是自己设置的,这里就不给出了,具体的大家可以自己设置一下css样式): $(document).ready(func

springmvc + jquery easyui实现分页显示

如有不明白的地方,戏迎加入QQ群交流:66728073 一,下载并导入jquery easyui的导 <link rel="stylesheet" type="text/css" href="<%=basePath%>js/jquery-easyui-1.4/themes/default/easyui.css"> <link rel="stylesheet" type="text/css

springmvc + jquery datatable + ajax实现动态分页查询

网上关于jquery datatable的例子很多,但结合springmvc的例子很少,搞了2天才把这个弄明白,现在记录下来,作为学习笔记. 1.导入所需文件 (1) jquery.dataTables.css (2) jquery.js (3) jquery.dataTables.js 2.datatable.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEnc

springmvc+mybatis+easyui分页

道德三黄五帝,功名夏侯商周.五霸七雄闹春秋,顷刻兴亡过手.清时几行名姓,北芒无数荒丘.前人播种后人收,说什么原创与否. 今天和大家分享一下springmvc+mybatis+easyui的分页实现.springmvc,mybatis的优缺点不做太多敖述大家都比较了解了,ssm框架整合的例子网上也有很多了,为什么还要写这篇文章那,主要是觉得大多过于零散配置方式又是千差万别,总结一下本文希望对遇到此问题的人有所帮助,前人播种后人收.当然程序开发没有觉得正确,谁也说不出一个正确的实现第N行代码是什么,

【MyBatis】MyBatis+SpringMVC+EasyUI整合分页

一.介绍 环境:MyBatis 3.0.x+Spring 3.0.x+EasyUI 采用SpringMVC+MyBatis框架整合的分页Demo,用的是首页这个:http://www.jeasyui.com/demo/main/index.php Demo结构如下: 再看一下效果: 二.项目详解: 前提是首先把所有的jar包导入进入,不管是用Maven或者手动都可以. 1.首先建立javabean,User.java: package com.bee.po; public class User