`
zqding
  • 浏览: 93396 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

struts2 + hibernate + spring + flexgrid 分页实现

阅读更多

struts2 + hibernate + spring + flexgrid 分页实现:

1、新建工程,添加struts2、hibernate、spring及对应版本必需jar包,要增加的jar文件列表如下:

jars

 

2、修改web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name>SSH Demo</display-name>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- 指定spring配置文件,默认从web根目录寻找配置文件,可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
	<!-- 对Spring容器进行实例化 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 编码过滤器(要放在struts2前面配置) -->
	<filter>
		<filter-name>encodeFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodeFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter>
		<filter-name>struts2</filter-name>
		<!--
			以前老版本用的是这个过滤器
			<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
		-->
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/500.jsp</location>
	</error-page>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

3、在src目录下增加新建一个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>
	<!--当struts.xml配置文件修改后,系统是否重新加载该文件,开发阶段打开此功能  -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!--
		指定WEB应用的编码集,相当于调用HttpServletRequest.setCharacterEncodint方法,如果使用了velocity或freemarker,它也用于指定输出的编码格式
	-->
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<!-- 指定请求后缀为.action,指定多个请求后缀用逗号分隔 -->
	<constant name="struts.action.extension" value="action" />
	<!--设置浏览器是否缓存静态内容,建议:开发阶段关闭,运行时开启  -->
	<constant name="struts.serve.static.browserCache" value="false" />
	<!--  开发提示:出错时打印更详细的信息-->
	<constant name="struts.devMode" value="true" />
	<!-- 这样配置后就可以再action的name元素中使用“/” -->
	<constant name="struts.enable.SlashesInActionNames" value="true" />
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<!-- 默认的视图主题 -->
	<constant name="struts.ui.theme" value="simple" />
	<!-- 资源文件 -->
	<constant name="struts.custom.i18n.resources" value="native" />
	<!-- Spring负责创建Action实例 -->
	<constant name="struts.objectFactory" value="spring" />
	<package name="ssh" extends="json-default">
		<action name="GetUsersList" class="GetUsersList">
			<result type="json" />
		</action>		
	</package>
</struts>
 

4、在src目录下增加新建一个hibernate.cfg.xml配置文件,其内容如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="connection.url">jdbc:mysql://localhost:3306/test</property>	
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
	<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
	<!--  
	<property name="hbm2ddl.auto">update</property>-->
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>	
	<mapping resource="com/starit/bean/TbUser.hbm.xml" /> 
</session-factory>
</hibernate-configuration>

 

5、在src目录下增加新建一个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="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation"
			value="classpath:hibernate.cfg.xml" />
	</bean>
	<bean id="userDAO" class="com.starit.dao.imp.UserDAOImpl"/>
	<bean id="userService" class="com.starit.service.imp.UserServiceImpl">
		<property name="userDAO">
			<ref local="userDAO"/>
		</property>
	</bean>
	<bean id="GetUsersList" class="com.starit.action.GetUsersList">
		<property name="userService">
			<ref local="userService"/>
		</property>
	</bean>
</beans>

 

6、在com/starit/bean/下建立类与表之间的映射关系TbUser.hbm.xml,其内容如下:

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.starit.bean">
    <class name="TbUser" table="tb_user" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
        	<column name="name" length="20"/>
        </property>
        <property name="gender" type="java.lang.String">
        	<column name="gender" length="6"/>
        </property>
        <property name="age" type="java.lang.Integer">
        	<column name="age"/>
        </property>
        <property name="birthday" type="java.sql.Date">
        	<column name="birthday"/>
        </property>
        <property name="phone" type="java.lang.String">
        	<column name="phone" length="11"/>
        </property>
        <property name="address" type="java.lang.String">
        	<column name="address" length="50"/>
        </property>
        <property name="username" type="java.lang.String">
            <column name="username" length="20" not-null="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

 

7、配置log4j,log4j.properties,内容如下:

log4j.rootLogger=error,CONSOLE,FILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d - %c -%-4r[%t]%-5p%c%x-%m%n


log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=file.log
log4j.appender.FILE.Append=false
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[framework]  %d - %c -%-4r [%t] %-5p %c %x -%m%n

 

8、下面是实现各层的代码:

 

/**
 * File   : TbUser.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.bean;

import java.io.Serializable;
import java.sql.Date;

public class TbUser implements Serializable {
	private static final long serialVersionUID = 1L;

	private Integer id;

	private String name;

	private String gender;

	private Integer age;

	private Date birthday;

	private String phone;

	private String address;

	private String username;

	private String password;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
}


/**
 * File   : UserDAO.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.dao;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.util.Page;

public interface UserDAO {
	public TbUser findByUsernamePassword(String username, String password);

	public Page findByPageNo(int pageNo, int pageSize);
	
	@SuppressWarnings("unchecked")
	public List getAllUsers()throws Exception;
	
	@SuppressWarnings("unchecked")
	public List getUsersByPage(int pageNo,int pageSize)throws Exception;
}


/**
 * File   : UserDAOImpl.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.dao.imp;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.starit.bean.TbUser;
import com.starit.dao.UserDAO;
import com.starit.util.HibernateSessionFactory;
import com.starit.util.Page;

public class UserDAOImpl implements UserDAO {
	private Session session = HibernateSessionFactory.getSession();

	public Page findByPageNo(int pageNo, int pageSize) {
		Page page = new Page();

		Query query = session.createQuery("select count(*) from TbUser");

		int count = Integer.parseInt(query.uniqueResult().toString());

		query = session.createQuery("from TbUser");
		query.setMaxResults(pageSize);
		query.setFirstResult((pageNo - 1) * pageSize);

		page.setList(query.list());
		page.setTotal(count);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);

		return page;
	}

	public TbUser findByUsernamePassword(String username, String password) {
		String hql = "from TbUser where username=? and password=?";
		Query query = session.createQuery(hql);
		query.setParameter(0, username);
		query.setParameter(1, password);
		return (TbUser) query.uniqueResult();
	}

	public List getAllUsers() throws Exception {
		String hql = "from TbUser";
		Query query = session.createQuery(hql);
		return query.list();
	}

	public List getUsersByPage(int pageNo,int pageSize) throws Exception {
		String hql = "from TbUser";
		Query query = session.createQuery(hql);
		query.setMaxResults(pageSize);
		query.setFirstResult((pageNo - 1) * pageSize);
		return query.list();
	}
	
	

}


/**
 * File   : UserService.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.service;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.util.Page;

public interface UserService {
	public TbUser findByUsernamePassword(String username, String password);

	public Page findByPageNo(int pageNo, int pageSize);
	
	@SuppressWarnings("unchecked")
	public List getAllUsers()throws Exception;
	
	@SuppressWarnings("unchecked")
	public List getUsersByPage(int pageNo,int pageSize)throws Exception;
}

/**
 * File   : UserServiceImpl.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.service.imp;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.dao.UserDAO;
import com.starit.service.UserService;
import com.starit.util.Page;

public class UserServiceImpl implements UserService {
	private UserDAO userDAO;
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public Page findByPageNo(int pageNo, int pageSize) {
		return userDAO.findByPageNo(pageNo, pageSize);
	}

	public TbUser findByUsernamePassword(String username, String password) {
		return userDAO.findByUsernamePassword(username, password);
	}

	@SuppressWarnings("unchecked")
	public List getAllUsers() throws Exception {
		
		return userDAO.getAllUsers();
	}

	@SuppressWarnings("unchecked")
	public List getUsersByPage(int pageNo, int pageSize) throws Exception {
		return userDAO.getUsersByPage(pageNo, pageSize);
	}
}

/**
 * File   : Page.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.util;

import java.util.List;

public class Page {
	private int total;

	private int pageSize;

	private int totalPage;

	private int pageNo;

	private int prePage;

	private int nextPage;

	private List list;

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public int getNextPage() {
		if (pageNo == totalPage) {
			nextPage = pageNo;
		} else {
			nextPage = pageNo + 1;
		}
		return nextPage;
	}

	public void setNextPage(int nextPage) {
		this.nextPage = nextPage;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPrePage() {
		if (pageNo == 1) {
			prePage = pageNo;
		} else {
			prePage = pageNo - 1;
		}
		return prePage;
	}

	public void setPrePage(int prePage) {
		this.prePage = prePage;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public int getTotalPage() {
		if (total % pageSize == 0) {
			totalPage = total / pageSize;
		} else {
			totalPage = total / pageSize + 1;
		}
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
}


/**
 * File   : HibernateSessionFactory.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   : 	
 */
package com.starit.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static Configuration configuration = new Configuration();
	private static org.hibernate.SessionFactory sessionFactory;
	private static String configFile = CONFIG_FILE_LOCATION;

	static {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("Error Creating SessionFactory...");
			e.printStackTrace();
		}
	}

	private HibernateSessionFactory() {
	}

	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

		return session;
	}

	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("Error Creating SessionFactory...");
			e.printStackTrace();
		}
	}

	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	public static Configuration getConfiguration() {
		return configuration;
	}
}

 

9、写flexgrid测试面页:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<title>Flexigrid</title>
		<link rel="stylesheet" type="text/css" href="resources/flexigrid/css/flexigrid/flexigrid.css" />
		<script type="text/javascript" src="resources/js/jquery1.3.2.js"></script>
		<script type="text/javascript" src="resources/flexigrid/flexigrid.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#flex1").flexigrid
						(
						{
						url: 'GetUsersList.action',
						dataType: 'json',
						colModel : [
							//{display: '<input type="checkbox" alt="全选" onclick="checkeds(this)">', name : 'getAll', width : 50, sortable : true, align: 'center'},
							{display: '编号', name : 'id', width : 40, sortable : true, align: 'center'},
							{display: '姓名', name : 'name', width : 40, sortable : true, align: 'center'},
							{display: '性别', name : 'gender', width : 180, sortable : true, align: 'left'},
							{display: '年龄', name : 'age', width : 120, sortable : true, align: 'left'},
							{display: '生日', name : 'birthday', width : 130, sortable : true, align: 'left', hide: true},
							{display: '电话', name : 'phone', width : 80, sortable : true, align: 'right'},
							{display: '地址', name : 'address', width : 80, sortable : true, align: 'right'}
							],
						searchitems : [
							{display: '编号', name : 'id'},
							{display: '姓名', name : 'name', isdefault: true}
							],
						sortname: "id",
						sortorder: "asc",
						usepager: true,
						title: '用户列表',
						useRp: true,
						checkbox : true,// 是否要多选框
						rowId : 'id',// 多选框绑定行的id
						rp: 10,
						showTableToggleBtn: true,//折叠
						resizable: true,
						striped: true, //是否显示斑纹效果,默认是奇偶交互的形式
						width: 700,
						height: 255
						}
						);   
				
			});

</script>
	</head>
	<body>
		<h1>
			Flexigrid Example Page
		</h1>
		<br />
		<br />
		<table id="flex1" style="display: none"></table>
		<br />
		<br />
	</body>
</html>

 

10,发布测试,测试结果如下如示:

分享到:
评论
5 楼 pug007 2013-01-18  
您好。请问您是如何保证输出的json是按照
{
"total":111, //数据总数
"page":4, //页码(第几页)
"rows":[
{"id":"1","cell":["a","b","c","e"]},
{"id":"2","cell":["a","b","c","e"]},
{"id":"3","cell":["a","b","c","e"]},
{"id":"4","cell":["a","b","c","e"]},
]}
这个格式的呢?
4 楼 zqding 2011-03-03  
sunnish 写道
好像没有ACTION代码,能贴一下ACTION的代码吗?

/**
* File   : GetUsersList.java
* Author : zqding
* Date   : 2010-7-23
* Version:
* Desc   :
*/
package com.starit.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;

import com.opensymphony.xwork2.ActionSupport;
import com.starit.bean.TbUser;
import com.starit.service.UserService;

public class GetUsersList extends ActionSupport {
private UserService userService;

public Integer getPage() {
return page;
}

public void setPage(Integer page) {
this.page = page;
}

public Integer getTotal() {
return total;
}

public void setTotal(Integer total) {
this.total = total;
}

@JSON(name = "rows")
public List<TbUser> getUserList() {
return userList;
}

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

public void setUserService(UserService userService) {
this.userService = userService;
}

private Integer page;
private Integer total;

private List<TbUser> userList;

@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
try {
HttpServletRequest request = ServletActionContext.getRequest();
int pageNo = Integer.valueOf(request.getParameter("page"));
int pageSize = Integer.valueOf(request.getParameter("rp"));

userList = this.userService.getUsersByPage(pageNo, pageSize);

this.total = this.userService.getAllUsers().size();
this.page = pageNo;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return SUCCESS;
}

public String deleteUsers() throws Exception {
try {
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("ids:>><<:" + request.getParameter("ids"));
if (!userService.deleteUserById(request.getParameter("ids"))) {
return "error";
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return SUCCESS;
}

}


3 楼 sunnish 2011-03-02  
好像没有ACTION代码,能贴一下ACTION的代码吗?
2 楼 zqding 2010-12-24  
lewter 写道
能把action转换json的格式贴出吗 ?

action转换json的过程是通过配置继承extends="json-default"它来实现的,你可以看一下json-default:
<package name="ssh" extends="json-default">
    <action name="GetUsersList" class="GetUsersList">
        <result type="json" />
    </action>
</package>

struts-plugin.xml:
<struts>
    <package name="json-default" extends="struts-default">
        <result-types>
            <result-type name="json" class="com.googlecode.jsonplugin.JSONResult"/>
        </result-types>
        <interceptors>
            <interceptor name="json" class="com.googlecode.jsonplugin.JSONInterceptor"/>
        </interceptors>
    </package>
</struts>
1 楼 lewter 2010-12-23  
能把action转换json的格式贴出吗 ?

相关推荐

Global site tag (gtag.js) - Google Analytics