`
king_tt
  • 浏览: 2121127 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

struts+spring+hibernate用jquery实现数据分页异步加载,页面不刷新

 
阅读更多

功能实现:分页,点击“加载更多”,将下一页的数据加载出来,页面不刷新。

用户entity类:

package com.test.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name="t_user",catalog="scott")
public class User implements Serializable{

private int user_id;

private String user_name;

private String user_sex;

private String user_class;

public User(){

}

public User(String user_name,String user_sex,String user_class){
this.user_name = user_name;
this.user_sex=user_sex;
this.user_class=user_class;
}

@Id
@Column(name="user_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="user_seq")
@SequenceGenerator(sequenceName="user_seq",name="user_seq")
public int getUser_id() {
return user_id;
}

public void setUser_id(int user_id) {
this.user_id = user_id;
}

@Column(name="user_name",length=24)
public String getUser_name() {
return user_name;
}

public void setUser_name(String user_name) {
this.user_name = user_name;
}

@Column(name="user_sex",length=4)
public String getUser_sex() {
return user_sex;
}

public void setUser_sex(String user_sex) {
this.user_sex = user_sex;
}

@Column(name="user_class",length=24)
public String getUser_class() {
return user_class;
}

public void setUser_class(String user_class) {
this.user_class = user_class;
}




}


接口类:

package com.test.user.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.test.model.User;

@Service
public interface UserService {

/*******
* 分页加载
* @param pagesize
* @param pagenow
* @return
* @throws Exception
*/
public List<User> getAllUserByPage(int pagesize,int pagenow) throws Exception;

/*********
* 获取用户总记录数
* @return
*/
public int getAllUserCount();

/*************
* 创建用户
*
* @param user
* @throws Exception
*/
public void createUser(User user) throws Exception;

}


实现上面接口

package com.test.user.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.test.model.User;
import com.test.user.dao.UserDao;
import com.test.user.service.UserService;

@Component
public class UserServiceImpl implements UserService {

@Resource
private UserDao userDao;

/*******
* 分页加载
* @param pagesize
* @param pagenow
* @return
* @throws Exception
*/
public List<User> getAllUserByPage(int pagesize,int pagenow) throws Exception{
return this.userDao.getAllUserByPage(pagesize, pagenow);
}

/*********
* 获取用户总记录数
* @return
*/
public int getAllUserCount(){
return this.userDao.getAllUserCount();
}

@Override
public void createUser(User user) throws Exception {
this.userDao.createUser(user);

}

}


Dao底层操作类:

package com.test.user.dao;

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

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.test.model.User;

@Repository
public class UserDao extends HibernateDaoSupport {

private JdbcTemplate jdbcTemplate;

@Resource
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Resource
public void setSessionFactoryOverride(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}


/*******
* 分页加载
* @param pagesize
* @param pagenow
* @return
* @throws Exception
*/
public List<User> getAllUserByPage(int pagesize,int pagenow) throws Exception{
Query q=this.getSession().createQuery("from User");
q.setFirstResult((pagenow-1)*pagesize);
q.setMaxResults(pagesize);
List li=q.list();
return li;
}

/*********
* 获取用户总记录数
* @return
*/
public int getAllUserCount(){
int count=0;
Query q=this.getSession().createQuery("select count(*) from User");
count=Integer.parseInt(q.uniqueResult().toString());
return count;
}

public void createUser(User user) throws Exception {
this.getHibernateTemplate().save(user);

}


public List<User> getAllUser() throws Exception {

// return this.getHibernateTemplate().find("from User");

// 用jdbcTemplate查询
List<User> list = new ArrayList<User>();
SqlRowSet rs = this.jdbcTemplate
.queryForRowSet("select user_id,user_name,user_sex,user_class from t_user");
while (rs.next()) {
User user = new User();
user.setUser_id(rs.getInt("user_id"));
user.setUser_name(rs.getString("user_name"));
user.setUser_sex(rs.getString("user_sex"));
user.setUser_class(rs.getString("user_class"));
list.add(user);
}
return list;
}

}


控制器Action类:

package com.test.user.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.test.model.User;
import com.test.user.service.UserService;

@Controller
public class UserAction extends ActionSupport {

@Resource
private UserService userService;

private List<User> userList = new ArrayList<User>();

public List<User> getUserList() {
return userList;
}

public void setUserList(List<User> userList) {
this.userList = userList;
}

/************************分页**************************/
private int pagesize;//每页显示多少条
private int currentPage;//当前页

public int getPagesize() {
return pagesize;
}

public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}

public int getCurrentPage() {
return currentPage;
}

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}

/*************
* 初始化加载用户数据
* @return
*/
public String getAllUserInit(){
try {
this.pagesize=7;//先加载 7 条数据
this.currentPage=1;//初始时设置当前页为1
this.userList=this.userService.getAllUserByPage(this.pagesize, this.currentPage);
} catch (Exception e) {
e.printStackTrace();
}
return "all";
}

/***********
* 分页-异步加载
* @return
*/
public String getAllUserByPage(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
//response.setHeader("Cache-Control", "no-cache");
try {
this.pagesize=7;//每次加载7条数据
System.out.println("当前页"+this.currentPage);
this.userList=this.userService.getAllUserByPage(this.pagesize, this.currentPage);
System.out.println("加载数据:"+this.userList.size());
PrintWriter out = response.getWriter();
JSONArray json=JSONArray.fromObject(this.userList);
out.print(json);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}


}


spring配置文件applicationContext-datasource.xml:

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


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="jdbcUrl"><value>jdbc:oracle:thin:@localhost:1521:ORCL</value></property>
<property name="user"><value>scott</value></property>
<property name="password"><value>tiger</value></property>
<property name="minPoolSize"><value>5</value></property>
<property name="maxPoolSize"><value>50</value></property>
<property name="maxIdleTime"><value>1800</value></property>
<property name="acquireIncrement"><value>5</value></property>
<property name="maxStatements"><value>0</value></property>
<property name="maxStatementsPerConnection"><value>100</value></property>
<property name="initialPoolSize"><value>5</value></property>
<property name="acquireRetryAttempts"><value>30</value></property>
<property name="breakAfterAcquireFailure"><value>false</value></property>
<property name="testConnectionOnCheckout"><value>false</value></property>
<property name="idleConnectionTestPeriod"><value>1800</value></property>
</bean>

<!-- 注入jdbcTemplate,查询数据时使用 -->
<bean id="jdbcTemplete" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>


</beans>

applicationContext-hibernate.xml

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


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.release_mode">auto</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.test.model.User</value>
</list>
</property>
</bean>

<bean name="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean name="baseTransaction" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="proxyTargetClass" value="true"></property>
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="edit*">PROPAGATION_REQUIRED</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="copy*">PROPAGATION_REQUIRED</prop>
<prop key="sync*">PROPAGATION_REQUIRED</prop>
<prop key="*">readOnly</prop>
</props>
</property>
</bean>

</beans>

applicationContext-beans.xml

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

<!--
<context:annotation-config></context:annotation-config>
-->
<!-- 如果配置了自动扫描,则上面的可以注释掉 -->
<context:component-scan base-package="com.test"></context:component-scan>


</beans>

struts的配置文件,struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" >
<struts>

<constant name="struts.ui.theme" value="simple" />
<constant name="struts.ui.templateDir" value="template" />
<constant name="struts.ui.templateSuffix" value="ftl" />

<constant name="struts.devMode" value="true"></constant>
<constant name="struts.configuration.xml.reload" value="true"></constant>

<package name="default" extends="struts-default">
<action name="userAction" class="com.test.user.action.UserAction">
<result name="all">/all.jsp</result>
</action>
</package>

</struts>


首页链接index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+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,keywword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<a href="${pageContext.request.contextPath }/userAction!getAllUserInit.action">异步加载显示</a>
</body>
</html>


数据显示页面:all.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>欢迎使用</title>

<META http-equiv="Expires" content="Mon, 26 Jul 1997 05:00:00 GMT">
<META http-equiv="Last-Modified" content="Sat, 10 Nov 1997 09:08:07 GMT">
<META http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">
<META http-equiv="Pragma" content="no-cache">
<style>
.stripe tr {height:30px; text-align: center; vertical-align: middle;font-size:12px;}
.oddTr{background-color: #D4D4D4;}
.evenTr{background-color: #EDEDED;}
.tr_mouseover{background-color: white;}
.tdWidth{width:20%;}
</style>

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.7.1.min.js"></script>

<script type="text/javascript">
$(function(){

//数据列表里的每个td宽度添加样式
$(".stripe td").addClass("tdWidth");

//让样式为.stripe的table下的第1行标头添加样式,eq(x),索引从0开始
$(".stripe").find("tr").eq(0).addClass("headTr");

//奇偶行变色
$(".stripe").find("tr:odd").addClass("oddTr");//偶数行
$(".stripe").find("tr:even").addClass("evenTr");//奇数行
//鼠标移上去变色
$(".stripe tr").mouseover(function(){
$(this).addClass("tr_mouseover");
})
.mouseout(function(){
$(this).removeClass("tr_mouseover");
});


//分页加载
var currentPage=1;
$("#loadTr").bind("click",function(){
currentPage=currentPage+1;//点一次"加载",当前页加 1
$("#loadTr td").replaceWith("<td><img src='${pageContext.request.contextPath}/images/loading.gif'/></td>");
$.ajax({
url:'${pageContext.request.contextPath}/userAction!getAllUserByPage.action',
type:'post',
data:{currentPage:currentPage},
dataType:'json',
success:function(data){

$.each(data,function(index,user){
$(".stripe").append("<tr><td>"+user.user_id+"</td><td>"+user.user_name+"</td><td>"+user.user_sex+"</td><td>"+user.user_class+"</td><td><img src='${pageContext.request.contextPath }/images/5.gif' style='vertical-align:middle;}'></img><a href='#'>编辑</td></tr>");
});

$("#loadTr td").replaceWith("<td>加载更多</td>");
if(data==null || data==""){
$("#loadTr td").replaceWith("<td>已经全部加载完毕</td>");
}

//奇偶行变色
$(".stripe").find("tr:odd").addClass("oddTr");//偶数行
$(".stripe").find("tr:even").addClass("evenTr");//奇数行
//鼠标移上去变色
$(".stripe tr").mouseover(function(){
$(this).addClass("tr_mouseover");
}).mouseout(function(){
$(this).removeClass("tr_mouseover");
});

}
});

});

});
</script>

</head>

<body>
<c:if test="${userList!=null}">
<table width="90%" cellpadding="0" cellspacing="0" style="border-collapse: collapse;border:1 solid #A0A0A0;" class="stripe" align="center">
<tr style="font-weight: bold;background-color: #0452A6;color:white;">
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>班级</td>
<td>操作</td>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.user_id }</td>
<td>${user.user_name }</td>
<td>${user.user_sex }</td>
<td>${user.user_class }</td>
<td><img src="${pageContext.request.contextPath }/images/5.gif" style="vertical-align:middle;}"></img><a href="#">编辑</a></td>
</tr>
</c:forEach>
</table>
<table width="90%" height="50" cellpadding="0" cellspacing="0" style="text-align: center;margin-top: 5;border-collapse: collapse;border:1 solid #A0A0A0;font-size:12px;" align="center">
<tr style="cursor:pointer" id="loadTr">
<td>加载更多</td>
</tr>
</table>
</c:if>
<c:if test="${userList==null}">
<table border="0" align="center" height="100">
<tr>
<td valign="middle">暂无相关数据</td>
</tr>
</table>
</c:if>
</body>
</html>


注意添加json有关的jar包



分享到:
评论

相关推荐

    Struts2+Spring+Hibernate+Ehcache+AJAX+JQuery+Oracle 框架集成用户登录注册Demo工程

    1.通过google ehcache-spring-annotatios.jar自动注解方式实现整合Spring+Ehcache。 2.Action里通过struts2-spring-plugin.jar插件自动根据名字注入。 3.Ajax无刷新异步调用Struts2,返回Json数据,以用户注册为例。...

    基于SSH2+EasyUI图书管理系统.zip

    后台采用技术: struts 2 + Spring + Hibernate (SSH2) 前台技术: jquery + easyui框架 所有的数据提交和查询都是通过ajax方式异步传输! 图书数据的添加和查询都是在这个js文件中实现 实现语言是javascript ...

    SSH2_EasyUI图书管理系统学生版 | 毕业设计

    后台采用技术: struts 2 + Spring + Hibernate (SSH2) 前台技术: jquery + easyui框架 所有的数据提交和查询都是通过ajax方式异步传输! 图书数据的添加和查询都是在这个js文件中实现 实现语言是javascript 下面...

    千方百计笔试题大全

    167、Prototype如何实现页面局部定时刷新? 40 168、Prototype如何为一个Ajax添加一个参数? 40 169、Ajax请求总共有多少种Callback? 41 170、Javascript如何发送一个Ajax请求? 41 171、AJAX都有哪些有点和缺点? ...

    java面试宝典

    167、Prototype如何实现页面局部定时刷新? 40 168、Prototype如何为一个Ajax添加一个参数? 40 169、Ajax请求总共有多少种Callback? 41 170、Javascript如何发送一个Ajax请求? 41 171、AJAX都有哪些有点和缺点? ...

    java面试题

    如果不使用Hibernate自带的分页,则采用什么方式分页? 62 71.16. hibernate中一对多配置文件返回的是什么? 63 71.17. hibernate拒绝连接、服务器崩溃的原因?最少写5个 63 71.18. Hibernate主键介绍 63 71.18.1. ...

    Java学习笔记-个人整理的

    {8.7}同步与异步}{126}{section.8.7} {8.8}Timer}{133}{section.8.8} {9}Java网络编程}{135}{chapter.9} {10}反射}{141}{chapter.10} {10.1}Class}{141}{section.10.1} {10.1.1}Field}{145}{subsection.10.1.1...

    Java面试宝典2020修订版V1.0.1.doc

    17、Hibernate是如何延迟加载的? 93 18、如果优化Hibernate? 93 19、什么是ORM? 94 20、Hibernate的主键生成策略? 94 21、Hibernate的级联操作 94 22、Hibernate有哪5个核心接口? 95 23、什么是重量级?什么是...

    java开源包3

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包4

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包8

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包1

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包11

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包2

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包6

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包5

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包10

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包7

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包9

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

    java开源包101

    GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以...

Global site tag (gtag.js) - Google Analytics