SpringMVC -jquery实现分页

效果图:

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

上一篇:实现div里的内容垂直居中


下一篇:NFS 系统的搭建