设备监造计划表:Jmesa | 出家如初,成佛有余
来源:百度文库 编辑:九乡新闻网 时间:2024/05/01 10:21:57
在jmesa中使用hsql支持复杂的hsql查询
Posted 五月 6, 2008 Comments(0)在目前的框架中,使用的是Hibernate Criteria来实现复杂的分页、排序、过滤等操作,基本上能够完成大部分复杂的查询分页、排序处理,但对于统计分析这样的复杂查询,Criteria实现还是有点力不从心,比较麻烦,尤其是在多表查询的情况下。
由于对于整型字段在目前在列表的输入框中输入过滤条件,会由于HttpServletRequest为String类型,而Hibernate为整型字段,导致对于在数据库中非String类型的字段过滤报错,因此暂时去除对过滤的支持功能,后续有空再研究解决方案,方法如下:
HtmlRow row = table.getRow();
row.setFilterable(false);
这样处理后,意味着我们在jmesa中实际上只需要处理分页、排序操作(导出为txt、excel、pdf等与此关系不大),因此对jmesa增加对hsql语句查询的支持,而不采用Criteria的方式,方法如下:
1. 对排序类HibernateSort
package com.mobilesoft.esales.dao.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
public class HibernateSort implements CriteriaCommand {
List public void addSort(String property, String order) { sorts.add(new Sort(property, order)); } public Criteria execute(Criteria criteria) { for (Sort sort : sorts) { buildCriteria(criteria, sort.getProperty(), sort.getOrder()); } return criteria; } public List getSortList(){ return this.sorts; } private void buildCriteria(Criteria criteria, String property, String order) { if (order.equals(Sort.ASC)) { criteria.addOrder(Order.asc(property)); } else if (order.equals(Sort.DESC)) { criteria.addOrder(Order.desc(property)); } } public static class Sort { public final static String ASC = “asc”; public final static String DESC = “desc”; private final String property; private final String order; public Sort(String property, String order) { this.property = property; this.order = order; } public String getProperty() { return property; } public String getOrder() { return order; } } } 增加getPersonWithFilterAndSort2和getPersonCountWithFilter2: public int getPersonCountWithFilter(final HibernateFilter filter) { Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(Person.class); criteria = filter.execute(criteria); criteria.setProjection(Projections.rowCount()).uniqueResult(); return criteria.uniqueResult(); } }); return count.intValue(); } public int getPersonCountWithFilter2(final HibernateFilter filter) { Long count = (Long) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { StringBuffer querySql=new StringBuffer(“select count(person) from Person as person “); Query query = session.createQuery(querySql.toString()); List list = query.list(); return list.get(0); } }); return count.intValue(); } public List List applications = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(Person.class); criteria = filter.execute(criteria); criteria = sort.execute(criteria); criteria.setFirstResult(rowStart); criteria.setMaxResults(rowEnd – rowStart); return criteria.list(); } }); return applications; } public List List applications = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { List sorts =sort.getSortList(); Iterator iterator=sorts.iterator(); StringBuffer sortSql=new StringBuffer(” “); int i=1; while(iterator.hasNext()){ HibernateSort.Sort field=(HibernateSort.Sort)iterator.next(); String property=field.getProperty(); String order=field.getOrder(); if(i>1) sortSql.append(” , “); else sortSql.append(” order by “); sortSql.append(property); sortSql.append(” “); sortSql.append(order); i++; } StringBuffer querySql=new StringBuffer(“select person from Person as person “); querySql.append(sortSql); Query query = session.createQuery(querySql.toString()); logger.fatal(“$HibernateCallback.doInHibernate(Session) “+querySql.toString()); //$NON-NLS-1$ query.setFirstResult(rowStart); query.setMaxResults(rowEnd-rowStart); List list = query.list(); return list; } }); return applications; } 在PersonService中增加接口声明 public int getPersonCountWithFilter2(HibernateFilter filter); public Collection 在PersonServiceImpl增加实现: public int getPersonCountWithFilter2(HibernateFilter filter) { return personDAO.getPersonCountWithFilter2(filter); } public Collection return personDAO.getPersonWithFilterAndSort2(filter, sort, rowStart, rowEnd); } 将获取数据修改为调用getPersonWithFilterAndSort2,获取总数修改为getPersonCountWithFilter2 if (!limit.isComplete()) { // deal with Criteria //int totalRows = personService.getPersonCountWithFilter(hibernateFilter); // deal with hsql int totalRows = personService.getPersonCountWithFilter2(hibernateFilter); tableFacade.setTotalRows(totalRows); } HibernateSort hibernateSort = getHibernateSort(limit); int rowStart = limit.getRowSelect().getRowStart(); int rowEnd = limit.getRowSelect().getRowEnd(); // deal with Criteria //Collection // deal with hsql Collection tableFacade.setItems(items); // Do not forget to set the items back on the tableFacade. http://code.google.com/p/jmesa/wiki/LimitExample 在使用jmesa作为组件来实现分页、导入、排序、过滤组件时候,对paging、sort、filter的处理,使用的是Hibernate的Criteria函数,对于单表使用Criteria方法相对容易,但对于多表操作,手册上没有现成的样例可以借鉴。总结一下Criteria的一些用法,以方便在对多表数据复杂操作时候也能够使用jmesa,简化分页、导出等日常操作。 public int getPersonCountWithFilter(final HibernateFilter filter) { Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(Person.class); criteria.add(Expression.eq(“id”,27)); criteria = filter.execute(criteria); criteria.setProjection(Projections.rowCount()).uniqueResult(); return criteria.uniqueResult(); } }); return count.intValue(); } public List List applications = (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(Person.class); criteria = filter.execute(criteria); criteria = sort.execute(criteria); criteria.setFirstResult(rowStart); criteria.setMaxResults(rowEnd – rowStart); return criteria.list(); } }); return applications; } CREATE TABLE `sys_user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `user_name` varchar(100) default NULL, `role_name` varchar(100) default NULL, PRIMARY KEY (`role_id`,`user_id`) ) ; INSERT INTO `sys_user_role` VALUES (’1′, ’1′, ‘liang1′, ‘admin1′); INSERT INTO `sys_user_role` VALUES (’2′, ’2′, ‘liang2′, ‘admin2′); INSERT INTO `sys_user_role` VALUES (’3′, ’3′, ‘liang3′, ‘admin3′); INSERT INTO `sys_user_role` VALUES (’4′, ’4′, ‘liang4′, ‘admin4′); INSERT INTO `sys_user_role` VALUES (’5′, ’5′, ‘liang5′, ‘anonymous’); INSERT INTO `sys_user_role` VALUES (’1′, ’5′, ‘liang1′, ‘admin5′); CREATE TABLE `sys_user` ( `user_id` int(11) NOT NULL, `mobile` varchar(15) default NULL, `imei` varchar(20) default NULL, `user_name` varchar(100) NOT NULL, `password` varchar(50) default NULL, `user_type` varchar(40) default ‘normal’ , `login_type` varchar(20) default NULL, `customer_id` int(11) default NULL, `customer_name` varchar(200) default NULL, `root_company_id` int(11) default NULL, `root_company_name` varchar(255) default NULL, `compayn_id` int(11) default NULL, `company_name` varchar(255) default NULL, `email` varchar(100) default NULL, `email2` varchar(100) default NULL, `nickname` varchar(100) default NULL, `sex` varchar(10) default NULL , `status` varchar(50) default NULL, `credit_amount` decimal(10,2) default NULL, `credit_rank` varchar(20) default NULL, `money` decimal(10,2) default NULL, `integral` decimal(10,2) default ’0.00′, `website` varchar(200) default NULL, `pwd_modify_date` datetime default NULL, `pwd_duration` varchar(10) default NULL, `signature` text, `twitter` varchar(255) default NULL, `qq` varchar(20) default NULL, `msn` varchar(50) default NULL, `icq` varchar(50) default NULL, `yahoo` varchar(30) default NULL, `gtalk` varchar(30) default NULL, `blog` varchar(255) default NULL, `interest` text, `safe_question` varchar(100) default NULL, `safe_answer` varchar(100) default NULL, `safe_question2` varchar(100) default NULL, `safe_answer2` varchar(100) default NULL, `safe_question3` varchar(100) default NULL, `safe_answer3` varchar(100) default NULL, `icon` varchar(100) default NULL, `icon2` varchar(100) default NULL, `icon3` varchar(100) default NULL, `is_test` tinyint(1) default NULL , `is_admin` tinyint(1) default NULL, `fax` varchar(20) default NULL, `home_phone` varchar(50) default NULL, `office_phone` varchar(20) default NULL, `birthday` char(19) default NULL, `vocation` varchar(20) default NULL, `education` varchar(50) default NULL, `address` varchar(255) default NULL, `postcode` varchar(20) default NULL, `description` text, `creator` varchar(40) default NULL, `begin_date` datetime default NULL, `end_date` datetime default NULL, `create_date` datetime default NULL, `modify_user` varchar(40) default NULL, `modify_date` datetime default NULL, `last_login_type` varchar(20) default NULL, `last_login_id` varchar(20) default NULL, `last_login_date` datetime default NULL, PRIMARY KEY (`user_id`) ) ; INSERT INTO `sys_user` VALUES (’1′, ’13911111111′, null, ‘liang1′, ‘liang1′, ‘normal’, null, null, ‘liang1′, null, null, null, null, null, null, null, null, null, null, null, null, ’0.00′, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); INSERT INTO `sys_user` VALUES (’2′, ’13922222222′, null, ‘liang2′, ‘liang2′, ‘normal’, null, null, ‘liang2′, null, null, null, null, null, null, null, null, null, null, null, null, ’0.00′, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); INSERT INTO `sys_user` VALUES (’3′, ’13933333333′, null, ‘liang3′, ‘liang3′, ‘normal’, null, null, ‘liang3′, null, null, null, null, null, null, null, null, null, null, null, null, ’0.00′, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); INSERT INTO `sys_user` VALUES (’4′, ’13944444444′, null, ‘liang4′, ‘liang4′, ‘normal’, null, null, ‘liang4′, null, null, null, ‘li’, null, null, null, null, null, null, null, null, ’0.00′, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); INSERT INTO `sys_user` VALUES (’5′, ’13955555555′, null, ‘liang5′, ‘liang5′, ‘normal’, null, null, ‘liang5′, null, null, null, null, null, null, null, null, null, null, null, null, ’0.00′, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); 注意: 由于在目前的数据模型及程序中并没有使用数据库的外键约束,直接通过程序来控制外键约束关系。因此在所有的hbm中并没有使用hibernate 的one-to-many关联。要使用Criteria实现多表较为复杂的操作,需要加上one-to-many映射。但这与目前的程序实现存在冲突,解决方法如下: 由于目前使用Criteria只用于查询及统计分析部分,可以单独建立一个映射文件及映射类,用于查询及统计分析操作,例如对于SysUser表,可以建立一个SysUser-jmesa.hbm.xml,对此映射文件,将 one-to-many: 由于只是演示,简单起见,直接用的是原有的映射文件及映射类。 xml version=”1.0″ encoding=”utf-8″?> PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> 省略掉其他内容 –> xml version=”1.0″ encoding=”utf-8″?> PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> Mapping file autogenerated by MyEclipse Persistence Tools –> import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.hibernate.FetchMode; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mobilesoft.esales.dao.hibernate.SysUserDAO; import com.mobilesoft.esales.model.SysUser; import com.mobilesoft.esales.model.SysUserRole; /** * Hibernate Criteria用法测试用例 * * @author liangchuan@mobile-soft.cn * */ public class TestCriteria extends TestCase { private static final Logger logger = Logger.getLogger(TestCriteria.class); private static ClassPathXmlApplicationContext context = null; private static SysUserDAO dao; static { context = new ClassPathXmlApplicationContext(new String[] { “applicationContext.xml”, “applicationContext-resources.xml”, “applicationContext-dao.xml”, “applicationContext-service.xml” }); } protected void setUp() throws Exception { } /** * 演示使用Criteria实现:select userId from SysUser as user */ public void testSelectId() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUser.class) .setProjection( Projections.projectionList().add( Projections.property(“userId”) ) ).list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ logger.fatal(“id is :”+iterator.next()); } } /** * 演示使用Criteria实现:select user.*,userRole.* from SysUser as user ,SysUserRole userRole where user.userId=userRole.id */ public void testJoin1() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUser.class) .setFetchMode(“userRoles”,FetchMode.JOIN).list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ SysUser user=(SysUser)iterator.next(); logger.fatal(“testJoin1:userid is :”+user.getUserId()+” userName is “+user.getUserName()); } } /** * 演示使用Criteria实现:select user.* ,userRole.* from SysUser as user ,SysUserRole userRole * where user.userId=userRole.id and user.userId=1 */ public void testJoin2() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUser.class) .setFetchMode(“userRoles”,FetchMode.JOIN) .add(Restrictions.eq(“userId”,1)) .list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ SysUser user=(SysUser)iterator.next(); logger.fatal(“testJoin2:userid is :”+user.getUserId()+” userName is “+user.getUserName()); } } /** * 演示使用Criteria实现:select user.* ,userRole.* from SysUser as user ,SysUserRole userRole * where user.userId=userRole.id and userRole.id.roleId=2 * 演示createAlias的使用 */ public void testJoin3() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUser.class) .setFetchMode(“userRoles”,FetchMode.JOIN) .createAlias(“userRoles”, “b”) .add(Restrictions.eq(“b.id.roleId”,2)) .list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ SysUser user=(SysUser)iterator.next(); logger.fatal(“testJoin3:userid is :”+user.getUserId()+” userName is “+user.getUserName()); } } /** * 演示使用Criteria实现:select count(userId) from SysUser as user ,SysUserRole userRole * where user.userId=userRole.id * 同时演示createAlias的使用 */ public void testJoin4() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUser.class) .setFetchMode(“userRoles”,FetchMode.JOIN) .setProjection( Projections.projectionList().add( Projections.count(“userId”) )) .list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ logger.fatal(“testJoin4:count(userId) is :”+iterator.next()); } } /** * 演示使用Criteria实现:select count(id.roleId) from SysUserRole userRole * 同时演示createAlias的使用 */ public void testJoin5() { dao = (SysUserDAO) context.getBean(“SysUserDAO”); List mylist=dao.getHibernateTemplate().getSessionFactory().openSession().createCriteria(SysUserRole.class) .setProjection( Projections.projectionList().add( Projections.count(“id.roleId”) )) .list(); Iterator iterator=mylist.iterator(); while(iterator.hasNext()){ logger.fatal(“testJoin5:count(roleId) is :”+iterator.next()); } } } 没有什么特别的,直接用myeclipse生成,然后在SysUser中添加上: private java.util.Set userRoles = new HashSet(); public java.util.Set getUserRoles() { return userRoles; } public void setUserRoles(java.util.Set userRoles) { this.userRoles = userRoles; } package com.mobilesoft.esales.model; /** * SysUserRole entity. * * @author MyEclipse Persistence Tools */ public class SysUserRole implements java.io.Serializable { // Fields private SysUserRoleId id; private String userName; private String roleName; // Constructors /** default constructor */ public SysUserRole() { } /** minimal constructor */ public SysUserRole(SysUserRoleId id) { this.id = id; } /** full constructor */ public SysUserRole(SysUserRoleId id, String userName, String roleName) { this.id = id; this.userName = userName; this.roleName = roleName; } // Property accessors public SysUserRoleId getId() { return this.id; } public void setId(SysUserRoleId id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getRoleName() { return this.roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } } http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/ http://www.devx.com/Java/Article/28754/1954 开始搭建新的基于struts2+spring+hibernate的技术架构,基于以前对eXtremeTable的好感,决定继续采用extremetable,而不选用displaytag和valuelist。用google搜索发现eXtremeTable的作者己不再更新eXtremeTable,其把精力转移到了新的项目-JMesa。 However, now that JMesa is up to release 2.1 I am only focusing my efforts on that library. The JMesa API has really turned into the library I have always wanted to create. With the introduction of the tags and facade in release 2.1 building tables is now easier than ever. I would encourage developers that are able to run in a JDK1.5 and JSP2.0 container to start using JMesa. If you are interested in a full explanation about how JMesa came about you can read more on the JMesa site. If you are more interested in what JMesa offers over the eXtremeTable read the features list. 基于Jmesa,从数据库表Person中查询出记录,能够实现分页、排序、导出功能。同时结合Jquery,利用ajax实现对数据的删除操作。 Jmesa: 2.3 Struts2 :2.0.11 Spring:2.5 Hibernate:3.2.5 Jquery:jquery-1.2.1.pack,jquery.bgiframe.pack Tomcat:5.5 Mysql :5.0 数据库、页面、JVM编码统一为GBK Jmesa表单组件使用演示样例 无特别的,省略 http://code.google.com/p/jmesa/w/list http://blog.csdn.net/jockCreate/archive/2008/02/20/2110310.aspx http://blog.csdn.net/czg18596/archive/2007/09/06/1774827.aspx http://www.javaeye.com/post/3626732. 对DAO类PersonDAO
3. PersonService及PersonServiceImpl
4. PersonAction
5、参考
Hibernate Criteria使用实例
Posted 四月 26, 2008 Comments(0) 1、目前使用Criteria用于取总数及排序过滤的用法例子
2、数据库表结构,以sys_user和sys_user_role为例子
3、hbm映射文件
3.1、SysUser.hbm.xml
3.2、SysUserRole.hbm.xml
4、测试用例
5、Model
5.1、SysUser.java
5.2、SysUserRole.java
6、参考文档
jmesa 使用指南
Posted 三月 9, 2008 Comments(8) 1、关于jmesa
2、基于struts2+spring+hibernate+jquery的jmesa分页实现样例
2.1、需求场景
2.2、环境说明
2.3、数据库表结构
CREATE TABLE `person` (`id` int(10) unsigned NOT NULL auto_increment,`firstName` varchar(45) NOT NULL,`lastName` varchar(45) NOT NULL,PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=76 DEFAULT CHARSET=latin1;
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt{background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }2.4、页面list.jsp
<%@ taglib prefix="s" uri="/struts-tags"%><%@ page language="java" errorPage="/error.jsp" pageEncoding="GBK" contentType="text/html;charset=GBK" %>
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt{background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }2.4、Action代码
package com.mobilesoft.esales.webapp.action;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import jxl.demo.CSV;import org.apache.commons.beanutils.BeanUtils;import org.jmesa.facade.TableFacade;import org.jmesa.facade.TableFacadeImpl;import org.jmesa.limit.Limit;import com.mobilesoft.esales.dao.hibernate.Person;import com.mobilesoft.esales.service.PersonService;import com.octo.captcha.service.CaptchaServiceException;import com.opensymphony.xwork2.Action;import static org.jmesa.limit.ExportType.CSV;import static org.jmesa.limit.ExportType.JEXCEL;import static org.jmesa.limit.ExportType.PDF;import org.jmesa.core.filter.DateFilterMatcher;import org.jmesa.core.filter.MatcherKey;import org.jmesa.facade.TableFacade;import org.jmesa.facade.TableFacadeImpl;import org.jmesa.limit.Limit;import org.jmesa.util.ItemUtils;import org.jmesa.view.component.Column;import org.jmesa.view.component.Row;import org.jmesa.view.component.Table;import org.jmesa.view.editor.BasicCellEditor;import org.jmesa.view.editor.CellEditor;import org.jmesa.view.editor.DateCellEditor;import org.jmesa.view.html.HtmlBuilder;import org.jmesa.view.html.component.HtmlColumn;import org.jmesa.view.html.component.HtmlRow;import org.jmesa.view.html.component.HtmlTable;import org.jmesa.view.html.editor.DroplistFilterEditor;import sun.text.CompactShortArray.Iterator;/** * 用于演示基于jmesa(http://code.google.com/p/jmesa/)的分页、排序组件的使用方法, * 在src/java/com/mobilesoft/esales/dao/hibernate/person.sql有Person表的测试数据 * @author liangchuan * @since 2008-03 */public class PersonAction extends BaseAction {private PersonService personService;private List
TableFacade tableFacade = new TableFacadeImpl("tableId", getRequest());//设定页面分页数据tableFacade.setItems(persons);//设定支持的查询结果导出格式为csv,excel,pdf格式tableFacade.setExportTypes(getResponse(), CSV, JEXCEL, PDF);tableFacade.setStateAttr("restore");Limit limit = tableFacade.getLimit();if (limit.isExported()) {export(tableFacade);return null;} else {String html = html(tableFacade);getRequest().setAttribute("myhtml", html);}return Action.SUCCESS;}private String html(TableFacade tableFacade) {// 设定表格属性,注意此处的url用于诸如增加、删除、修改、查询操作,并不是实际的数据库表属性,//但表单需要有对应的po对新,因此需要在Person中增加此属性tableFacade.setColumnProperties("id", "firstName", "lastName", "url");HtmlTable table = (HtmlTable) tableFacade.getTable();table.setCaption("测试用户信息列表");table.getTableRenderer().setWidth("600px");HtmlRow row = table.getRow();HtmlColumn id = row.getColumn("id");id.setTitle("id");HtmlColumn firstName = row.getColumn("firstName");firstName.setTitle("属性1");HtmlColumn lastName = row.getColumn("lastName");lastName.setTitle("属性2");HtmlColumn deleteAction = row.getColumn("url");deleteAction.setTitle("操作");// Using an anonymous class to implement a custom editor.// 用于演示在表格中增加超链接firstName.getCellRenderer().setCellEditor(new CellEditor() {public Object getValue(Object item, String property, int rowcount) {Object value = new BasicCellEditor().getValue(item, property,rowcount);HtmlBuilder html = new HtmlBuilder();html.a().href().quote().append("http://www.mobile-soft.cn").quote().close();html.append(value);html.aEnd();return html.toString();}});// Using an anonymous class to implement a custom editor.//用于演示在表格中增加javascript操作,通过jquery来实现ajax式的删除操作deleteAction.getCellRenderer().setCellEditor(new CellEditor() {public Object getValue(Object item, String property, int rowcount) {Object value = new BasicCellEditor().getValue(item, property,rowcount);HtmlBuilder html = new HtmlBuilder();//取得每一行的id号Object id = ItemUtils.getItemValue(item, "id");String js=" onclick='javascript:del(\"tableId\","+id+") '";html.a().append(js).href().quote().append(getRequest().getContextPath()+"/remove.action?id="+id).quote().close();html.append("删除");html.aEnd();return html.toString();}});return tableFacade.render(); // Return the Html.}private void export(TableFacade tableFacade) {tableFacade.setColumnProperties("id", "firstName", "lastName");Table table = tableFacade.getTable();table.setCaption("Persons Test");Row row = table.getRow();Column id = row.getColumn("id");id.setTitle("id");Column firstName = row.getColumn("firstName");firstName.setTitle("First Name");Column lastName = row.getColumn("lastName");lastName.setTitle("Last Name");tableFacade.render();}public String login() {Boolean isResponseCorrect = Boolean.FALSE;// remenber that we need an id to validate!String captchaId = getSession().getId();// retrieve the responseString response = getRequest().getParameter("j_captcha_response");// Call the Service methodtry {isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId, response);} catch (CaptchaServiceException e) {// should not happen, may be thrown if the id is not valid}if (!isResponseCorrect) {return Action.LOGIN;}return execute();}public String save() {this.personService.save(person);this.person = new Person();return execute();}/** * 用于演示ajax方式删除操作,参看pages/list.jsp * @return */public String remove() {String deleteId = getRequest().getParameter("id");if (deleteId != null) {personService.remove(Integer.parseInt(deleteId));}this.persons = personService.findAll();TableFacade tableFacade = new TableFacadeImpl("tableId", getRequest());tableFacade.setItems(persons); // set the itemstableFacade.setExportTypes(getResponse(), CSV, JEXCEL, PDF);tableFacade.setStateAttr("restore");Limit limit = tableFacade.getLimit();if (limit.isExported()) {export(tableFacade);return null;} else {String html = html(tableFacade);getRequest().setAttribute("myhtml", html);}return Action.SUCCESS;}public List
2.5、Service、DAO层代码
2.6、Model代码
package com.mobilesoft.esales.dao.hibernate;/** * Person entity. * * @author liangchuan
*/public class Person implements java.io.Serializable {// Fieldsprivate Integer id;private String firstName;private String lastName;private String url="";// Constructors/** default constructor */public Person() {}/** full constructor */public Person(String firstName, String lastName) {this.firstName = firstName;this.lastName = lastName;}// Property accessorspublic Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}public String getFirstName() {return this.firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return this.lastName;}public void setLastName(String lastName) {this.lastName = lastName;}/** * @return the url */public String getUrl() {return url;}/** * @param url the url to set */public void setUrl(String url) {this.url = url;}}
2.7、Struts.xml
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt{background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }3、jmesa研究
4、参考资料