当前位置: 代码迷 >> JavaScript >> 分页展示 (SSH实现+Ajax读取json)
  详细解决方案

分页展示 (SSH实现+Ajax读取json)

热度:465   发布时间:2012-12-26 14:39:28.0
分页显示 (SSH实现+Ajax读取json)
数据分页显示(SSH实现+Ajax读取json)


1.bean类:pageInfo.java
package com.org.momo.bean;

public class PageInfo {
     private Integer pageRows ;    //每页行数
     private Integer currentPage ; //当前页数
     private Integer pageTotal ;   //页面总数
     
     
	public Integer getPageRows() {
		return pageRows;
	}
	public void setPageRows(Integer pageRows) {
		this.pageRows = pageRows;
	}
	public Integer getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(Integer currentPage) {
		this.currentPage = currentPage;
	}
	public Integer getPageTotal() {
		return pageTotal;
	}
	public void setPageTotal(Integer pageTotal) {
		this.pageTotal = pageTotal;
	}
   
}




2.dao接口:
package com.org.momo.dao;

import java.util.List;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;

public interface TeamDao {
    public void insert(Team team) throws Exception ;
    public void deleteById(Integer id) throws Exception ;
    public Team findById(Integer id) throws Exception ;
    public List<Team> findAll() throws Exception ;
    public void update(Team team) throws Exception ;
    public List<Team> findAllPage(PageInfo pageInfo) throws Exception ;
}





3.dao接口实现类,有两种实现底层数据查询: 
  a.Hibernate自身实现 
   b.spring对Hibernate的支持HibernateTemplate实现

a.Hibernate自身实现:
package com.org.momo.dao.hibernateTemplate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;
import com.org.momo.util.HibernateUtil;
/**
 *   此方法为Hibernate自身的类实现底层数据访问
 *   另外一种实现方式就是:spring对Hibernate的支持HibernateTemplate(见下一个
 *   类 TeamDaoHibernateTemplate.java
 *   )
 * */

public class TeamDaoHibernate implements TeamDao {
	private SessionFactory sessionFactory;
	
	public TeamDaoHibernate() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	public void insert(Team team) throws Exception {
		Session session = sessionFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
		session.save(team);
		transaction.commit();
		
		session.close() ;
	}

	public void deleteById(Integer id) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		String hql = "delete from Team where id=?";
		Query query = session.createQuery(hql);
		query.setInteger(0, id);
		query.executeUpdate();
		
		transaction.commit();
		session.close();
	}

	public void update(Team team) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		session.merge(team);
		
		transaction.commit();
		session.close();
	}

	public List<Team> findAll() throws Exception {
		List<Team> teams = null;
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("from Team");
		teams = query.list();
		
		session.close();
		
		return teams;
	}

	public Team findById(Integer id) throws Exception {
		Team team = null;
		
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from Team where id=?");
		query.setInteger(0, id);
		team = (Team)query.uniqueResult();
		session.close();
		
		return team;
	}

	public List<Team> findAllPage(PageInfo pageInfo) throws Exception {
		List<Team> teams = null;
		
		Session session = sessionFactory.openSession();
		
		Query queryTotal = session.createQuery("select count(id) from Team");
		int rowCount = ((Long)queryTotal.uniqueResult()).intValue() ;  //先转换为Long 在转换为int
		int pageTotal = rowCount/pageInfo.getPageRows();
		if(rowCount%pageInfo.getPageRows() > 0) {
			pageTotal++;
		}
		pageInfo.setPageTotal(pageTotal);
		
		Query query = session.createQuery("from Team");
		query.setFirstResult(pageInfo.getPageRows()*(pageInfo.getCurrentPage()-1));
		query.setMaxResults(pageInfo.getPageRows());
		teams = query.list();
		
		session.close();
		
		return teams;
	}

}



package com.org.momo.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;


public class HibernateUtil {
	  private static final SessionFactory sessionFactory;
      static{
    	  try{
    		  //初始化hibernate.cfg.xml配置,建立数据库连接
    		  sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    	  }catch(Exception e){
    		  e.printStackTrace() ;
    		  throw new ExceptionInInitializerError(e) ;
    	  }
      }
      
      public static SessionFactory getSessionFactory(){
    	  return sessionFactory ;
      }
}


[color=brown]applicationContext.xml文件配置映射:
<bean id="teamDao" class="com.org.momo.dao.hibernateTemplate.TeamDaoHibernate"></bean>[/color]


b.spring对Hibernate的支持HibernateTemplate实现:
package com.org.momo.dao.hibernateTemplate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;

public class TeamDaoHibernateTemplate extends HibernateDaoSupport implements TeamDao {

	public void deleteById(Integer id) throws Exception {
        Team team = this.getHibernateTemplate().load(Team.class, id) ;
		this.getHibernateTemplate().delete(team) ;
	}

	public List<Team> findAll() throws Exception {
		return this.getHibernateTemplate().loadAll(Team.class);
	}

	public Team findById(Integer id) throws Exception {
		List<Team> teams = this.getHibernateTemplate().find("from Team where id=?",id) ;
		if(!teams.isEmpty()){
			return teams.get(0) ;
		}else{
		return null;
		}
	}

	public void insert(Team team) throws Exception {
		this.getHibernateTemplate().save(team) ;
	}

	public void update(Team team) throws Exception {
		this.getHibernateTemplate().update(team);
	}

	public List<Team> findAllPage(final PageInfo pageInfo) throws Exception {
		List<Team> teams = null;
		
		int rowTotal = ((Long)this.getHibernateTemplate().find("select count(id) from Team").get(0)).intValue();
		int pageTotal = rowTotal/pageInfo.getPageRows();
		if(rowTotal%pageInfo.getPageRows() > 0) {
			pageTotal++;
		}
		pageInfo.setPageTotal(pageTotal);
		
		teams = this.getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery("from Team");
				query.setFirstResult(pageInfo.getPageRows()*(pageInfo.getCurrentPage()-1));
				query.setMaxResults(pageInfo.getPageRows());
				return query.list();
			}
			
		});
		
		return teams;
	}

}



spring的配置文件applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="teamService" class="com.org.momo.service.impl.TeamServiceImpl">
		<property name="teamDao" ref="teamDao"></property>
	</bean>
	<bean id="adminService" class="com.org.momo.service.impl.AdminServiceImpl">
		<property name="adminDao" ref="adminDao"></property>
	</bean>
    <bean id="logService" class="com.org.momo.service.impl.LogServiceImpl">
        <property name="logDao" ref="logDao"></property>
    </bean>
    <bean id="studentService" class="com.org.momo.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"></property>
    </bean>
    
    [color=brown]<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
    
    
    <bean id="teamDao" class="com.org.momo.dao.hibernateTemplate.TeamDaoHibernateTemplate">
		<property name="hibernateTemplate" ref="hibernateTemplate"/>
	</bean>[/color]    <bean id="adminDao" class="com.org.momo.dao.hibernateTemplate.AdminDaoHibernateTemplate">
        <property name="hibernateTemplate" ref="hibernateTemplate"/>
    </bean>
    <bean id="logDao" class="com.org.momo.dao.hibernateTemplate.LogDaoHibernateTemplate">
        <property name="hibernateTemplate" ref="hibernateTemplate"/>
    </bean>
    <bean id="studentDao" class="com.org.momo.dao.hibernateTemplate.StudentDaoHibernateTemplate">
        <property name="hibernateTemplate" ref="hibernateTemplate"/>
    </bean>
    

    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
    </bean>
</beans>


4.业务层:service接口和接口实现类serviceImpl:
package com.org.momo.service;

import java.util.List;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;

public interface TeamService {
   public TeamDao getTeamDao() ;
   public void setTeamDao(TeamDao teamDao) ;
   public void addTeam(Team team) throws Exception ;
   public void deleteTeam(Integer id) throws Exception ;
   public Team getTeam(Integer id) throws Exception ;
   public List<Team> getTeams() throws Exception ;
   public void updateTeam(Team team) throws Exception ;
   public List<Team> pageTeams(PageInfo page) throws Exception ;
}


package com.org.momo.service.impl;

import java.util.List;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;
import com.org.momo.service.TeamService;

public class TeamServiceImpl implements TeamService {
    private TeamDao teamDao ;
	
	public void addTeam(Team team) throws Exception {
       teamDao.insert(team) ;
	}

	public void deleteTeam(Integer id) throws Exception {
       teamDao.deleteById(id) ;
	}

	public Team getTeam(Integer id) throws Exception {
		return teamDao.findById(id) ;
	}

	public TeamDao getTeamDao() {
		return teamDao;
	}

	public List<Team> getTeams() throws Exception {
		return teamDao.findAll() ;
	}

	public void setTeamDao(TeamDao teamDao) {
        this.teamDao = teamDao ;
	}

	public void updateTeam(Team team) throws Exception {
        teamDao.update(team) ;
	}

	public List<Team> pageTeams(PageInfo page) throws Exception {
		return teamDao.findAllPage(page) ;
	}

}




5.控制层Action类:
package com.org.momo.action.team;

import java.io.PrintWriter;
import java.util.List;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.service.TeamService;
import com.org.momo.util.JsonUtil;
import com.org.momo.util.XmlUtil;

public class ViewTeamsJSONAction extends ActionSupport {
	@Resource
	private TeamService teamService;
	private PageInfo pageInfo ;
	
	public PageInfo getPageInfo() {
		return pageInfo;
	}

	public void setPageInfo(PageInfo pageInfo) {
		this.pageInfo = pageInfo;
	}

	public String execute() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain;charset=GBK");
		try {
			PrintWriter out = response.getWriter();
			
			//设置每页显示多少行
			pageInfo.setPageRows(5) ;
			//获取所有小组
			List<Team> teams = teamService.pageTeams(pageInfo) ;
			out.println(JsonUtil.teamsToJsonPage(teams, pageInfo));  //将document转换为String输出
			out.flush() ;
			out.close() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
		
		return NONE;
	}
}



6.struts2的配置文件struts.xml
   <?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0 //EN"
  "struts-2.1.7.dtd">
<struts>
<constant name="struts.i18n.encoding" value="GBK"></constant>

<package name="team" namespace="/team" extends="struts-default">
    <interceptors>
        <interceptor name="LogInterceptor" class="com.org.momo.interceptor.LogInterceptor"></interceptor>
        <interceptor-stack name="TeamInterceptor">
          <interceptor-ref name="defaultStack"></interceptor-ref>
          <interceptor-ref name="LogInterceptor"></interceptor-ref>
        </interceptor-stack>
    </interceptors> 
        <default-interceptor-ref name="TeamInterceptor"></default-interceptor-ref>

    <action name="TeamNameCheck" class="com.org.momo.action.team.TeamNameCheckAction">
	</action>
	<action name="ViewTeamsXML" class="com.org.momo.action.team.ViewTeamsXMLAction">
	</action>
	<action name="ViewTeamsXSL" class="com.org.momo.action.team.ViewTeamsXSLAction">
	</action>
	[color=red]<action name="ViewTeamsJSON" class="com.org.momo.action.team.ViewTeamsJSONAction">
	</action>[/color]	<action name="ViewTeams" class="com.org.momo.action.team.ViewTeamsAction">
		<result name="success">/team/viewTeams.jsp</result>
		<result name="error">/team/exception.jsp</result>
	</action>
	<action name="DeleteTeam" class="com.org.momo.action.team.DeleteTeamAction">
		<result name="success" type="redirect">/team/ViewTeams</result>
		<result name="error">/team/exception.jsp</result>
	</action>
	<action name="ViewUpdateTeam" class="com.org.momo.action.team.UpdateTeamViewAction">
		<result name="success">/team/updateTeam.jsp</result>
		<result name="error">/team/exception.jsp</result>
	</action>
	<action name="UpdateTeam" class="com.org.momo.action.team.UpdateTeamAction">
		<result name="success" type="redirect">/team/ViewTeams</result>
		<result name="error">/team/exception.jsp</result>
	</action>
	<action name="AddTeam" class="com.org.momo.action.team.AddTeamAction">
		<result name="success" type="redirect">/team/ViewTeams</result>
		<result name="error">/team/exception.jsp</result>
		<result name="input">/team/addTeam.jsp</result>
	</action>
</package>


<package name="admin" namespace="/admin" extends="struts-default">
    <interceptors>
        <interceptor name="LogInterceptor" class="com.org.momo.interceptor.LogInterceptor"></interceptor>
        <interceptor-stack name="TeamInterceptor">
          <interceptor-ref name="defaultStack"></interceptor-ref>
          <interceptor-ref name="LogInterceptor"></interceptor-ref>
        </interceptor-stack>
    </interceptors> 
        <default-interceptor-ref name="TeamInterceptor"></default-interceptor-ref>
        
    <action name="Login" class="com.org.momo.action.admin.LoginAction">
        <result name="success">/index.jsp</result>
        <result name="input">/login.jsp</result>
        <result name="error">/team/exception.jsp</result>
    </action>
    <action name="UpdatePassword" class="com.org.momo.action.admin.UpdatePasswordAction">
        <result name="success">/team/index.jsp</result>
        <result name="error">/team/exception.jsp</result>
    </action>
</package>

<package name="student" namespace="/student" extends="struts-default">
   <interceptors>
        <interceptor name="LogInterceptor" class="com.org.momo.interceptor.LogInterceptor"></interceptor>
        <interceptor-stack name="TeamInterceptor">
          <interceptor-ref name="defaultStack"></interceptor-ref>
          <interceptor-ref name="LogInterceptor"></interceptor-ref>
        </interceptor-stack>
    </interceptors> 
        <default-interceptor-ref name="TeamInterceptor"></default-interceptor-ref>

    <action name="AddStudent" class="com.org.momo.action.student.AddStudentAction">
        <result name="success" type="redirect">/student/ViewStudents</result>
        <result name="error">/student/exception.jsp</result>
    </action>
    <action name="ViewStudents" class="com.org.momo.action.student.ViewStudentsAction">
        <result name="success">/student/viewStudent.jsp</result>
        <result name="error">/student/exception.jsp</result>
    </action>
    <action name="DeleteStudent" class="com.org.momo.action.student.DeleteStudentAction">
        <result name="success" type="redirect">/student/ViewStudents</result>
        <result name="error">/student/exception.jsp</result>
    </action>
    <action name="ViewUpdateStudent" class="com.org.momo.action.student.ViewUpdateStudentAction">
        <result name="success">/student/updateStudent.jsp</result>
        <result name="error">/student/exception.jsp</result>
    </action>
    <action name="UpdateStudent" class="com.org.momo.action.student.UpdateStudentAction">
        <result name="success" type="redirect">/student/ViewStudents</result>
        <result name="error">/student/exception.jsp</result>
    </action>
</package>
</struts>



7.JSONUtil处理类:

package com.org.momo.util;

import java.util.List;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Student;
import com.org.momo.bean.Team;

public class JsonUtil {

	public static String teamsToJsonPage(List<Team> teams,PageInfo pageInfo)throws Exception
	{
		String jsonStr = null;
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append("{");
		//处理teams
		//teams开始
		strBuffer.append("\"teams\":[");
		//处理teams
		for(int i=0;i<teams.size();i++)
		{
			Team team = teams.get(i); 
			//team开始
			strBuffer.append("{");
			//处理id
			strBuffer.append("\"id\":");
			strBuffer.append(team.getId());
			strBuffer.append(",");
			//处理name
			strBuffer.append("\"name\":\"");
			strBuffer.append(team.getName());
			strBuffer.append("\",");
			//处理leader
			strBuffer.append("\"leader\":\"");
			strBuffer.append(team.getLeader());
			strBuffer.append("\",");
			//处理slogan
			strBuffer.append("\"slogan\":\"");
			strBuffer.append(team.getSlogan());	
			strBuffer.append("\",");
			//处理members
			strBuffer.append("\"members\":\"") ;
			if(team.getMembers()!=null){
				int j=0 ;
				for(Student stu:team.getMembers()){
					j++ ;
					strBuffer.append(stu.getName()) ;
					if(j<team.getMembers().size()){
						strBuffer.append(",") ;
					}
				}
			}
			strBuffer.append("\"") ;
			
			//team结束
			if(i<teams.size()-1)
			{
			strBuffer.append("},");
			}
			else
			{
				strBuffer.append("}");
			}
			
		}
		
		//teams结束
		strBuffer.append("],");
		
		//pageInfo开始
		strBuffer.append("\"pageInfo\":{");
		//处理pageRows 
		strBuffer.append("\"pageRows\":");
		strBuffer.append(pageInfo.getPageRows());
		strBuffer.append(",");
		//处理currentPage
		strBuffer.append("\"currentPage\":");
		strBuffer.append(pageInfo.getCurrentPage());
		strBuffer.append(",");
		//处理pageTotal
		strBuffer.append("\"pageTotal\":");
		strBuffer.append(pageInfo.getPageTotal());
		
	
	    //pageInfo结束
		strBuffer.append("}");
		//json结束
		strBuffer.append("}");
		jsonStr = strBuffer.toString();
		return jsonStr;
	}
}



8.前台界面JSP+javascript+AJAX(读取保存了teamsinfo和pageInfo的JSON字符串)
  <%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>显示小组(Ajax)</title>
<link rel="stylesheet" type="text/css" href="css/team.css" />
<script type="text/javascript" src="js/trim.js"></script>
<script type="text/javascript">
function startRequest(pageNo) {
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		handleStateChange(pageNo);
	};
	xmlHttp.open("POST","team/ViewTeamsJSON",true);
	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlHttp.send("pageInfo.currentPage=" + pageNo);
}

function handleStateChange(pageNo) {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
		
			 var text = xmlHttp.responseText ;
			 var jsonObject = eval ("(" + text + ")");
			 var teamTable = document.getElementById("teamTable");
			 //alert(text) ;
			 
			  //清除原有数据
		   for(var i=teamTable.rows.length-1;i>0;i--){
		       teamTable.deleteRow(i) ;
		   }
			 
			 for(var i=0;i<jsonObject.teams.length;i++) {
			     //为表格加一行
				var tr = teamTable.insertRow(i+1);
			    
			    //为表格加一个格
				var td = tr.insertCell(0);
				td.innerHTML = jsonObject.teams[i].id;
				
				//为表格加一个格
				var td = tr.insertCell(1);
				td.innerHTML = jsonObject.teams[i].name;
				
				//为表格加一个格
				var td = tr.insertCell(2);
				td.innerHTML = jsonObject.teams[i].leader;
				
				//为表格加一个格
				var td = tr.insertCell(3);
				td.innerHTML = jsonObject.teams[i].slogan;
				
				//为表格加一个格
				var td = tr.insertCell(4);
				td.innerHTML = jsonObject.teams[i].members;
				
				//为表格加一个格
				var td = tr.insertCell(5);
				td.innerHTML = "<a href='team/ViewUpdateTeam?team.id="+jsonObject.teams[i].id+"'>修改</a>  <a href='team/DeleteTeam?team.id="+jsonObject.teams[i].id+"'>删除</a>";
			 }
			 
			 //处理页面跳转的连接
			var pageDiv = document.getElementById("page") ;
			var pageTotal = jsonObject.pageInfo.pageTotal ;
			var pageHtml =" ";
			if(pageNo>1){
			pageHtml += "<a href='javascript:startRequest("+ 1 +")'>首页</a>  " ;     //可以改为上一页   "1"  改为:   (pageNo-1)
			 } 
		    for(i = 0 ; i < pageTotal; i ++){
               pageHtml += "<a href = 'javascript:startRequest("+(i+1)+")'>"+(i+1)+"</a>   ";
              } 
			   
			 if(pageNo < pageTotal) {
				pageHtml += " <a href='javascript:startRequest(" + pageTotal + ")'>尾页</a>";    //可以改为下一页   pageTotal  改为:  (pageNo+1)
			   }
			pageDiv.innerHTML = pageHtml ;
		}
	}
}
</script>
</head>
<body onload="startRequest(1)">
<div id="top">
<h1>显示小组</h1>
</div>
<div id="content">
<table border="1" id="teamTable">
<tr>
<th>ID</th><th>组名</th><th>组长</th><th>口号</th><th>成员</th><th>操&nbsp;&nbsp;作</th>
</tr>
</table>
</div>
<p><div id="page"></div>
<p><a href="team/index.jsp">返回小组管理</a>
</body>
</html>
  相关解决方案