上篇 把项目(Crud)整体搭建完成,本章继续写项目的实现。
1、创建数据库表People:
create table PEOPLE
(
ID NUMBER primary key,
NAME NVARCHAR2(10),
AGE NUMBER,
BIRTHDAY DATE,
GENDER NVARCHAR2(10),
HOBBY NVARCHAR2(30)
)
2、创建实体类:
/** * @package :example.crud.entity<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:26:32<br> */ package example.crud.entity; import java.util.Date; import org.apache.tapestry5.beaneditor.NonVisual; /** * @package :example.crud.entity<br> * @file :People.java<br> * @describe :用户 实体类<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:26:32<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public class People { /** * */ public People() { // TODO Auto-generated constructor stub birthday = new Date(); } /** * ID 好 */ @NonVisual private int id; /** * 姓名 */ private String name; /** * 年龄 */ private int age; /** * 生日 */ private Date birthday; /** * 性别 */ private Gender gender; /** * 兴趣爱好 */ private String hobby; public int getId() { return id; } public void setId(int id) { this.id = id; } // 其他属性的set,get方法 // ...... @Override public String toString() { return "People [id=" + id + ", name=" + name + ", age=" + age + ", birthday=" + birthday + ", gender=" + gender + ", hobby=" + hobby + "]"; } }创建 枚举类型代表性别:
package example.crud.entity; public enum Gender { 男, 女; }创建 查询帮助实体:
/** * @package :example.register.entity<br> * @author :wanglongjie<br> * @createDate :2015年8月18日下午1:43:01<br> */ package example.crud.entity; /** * @package :example.register.entity<br> * @file :QueryPeople.java<br> * @describe :查询实体<br> * @author :wanglongjie<br> * @createDate :2015年8月18日下午1:43:01<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public class QueryPeople { private String flag; private Gender gender; private int minAge = 0; private int maxAge = 100; private String name; private String hobby; private String minBirthday; private String maxBirthday; public QueryPeople() { // TODO Auto-generated constructor stub minAge = 0; maxAge = 100; flag = ""; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } // 其他属性的set,get方法 // ...... @Override public String toString() { return "QueryPeople [flag=" + flag + ", gender=" + gender + ", minAge=" + minAge + ", maxAge=" + maxAge + ", name=" + name + ", hobby=" + hobby + ", minBirthday=" + minBirthday + ", maxBirthday=" + maxBirthday + "]"; } }3、创建接口,及完成接口实现类:
/** * @package :example.crud.dao<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:26:19<br> */ package example.crud.dao; import java.util.List; import java.util.Map; import example.crud.entity.People; /** * @package :example.crud.dao<br> * @file :PeopleDao.java<br> * @describe :用户Dao接口<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:26:19<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public interface PeopleDao { /** * * @method :save<br> * @describe :保存用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:30:14 <br> * @param people * @return boolean */ boolean save(People people); /** * * @method :delete<br> * @describe :删除用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:30:23 <br> * @param people * @return boolean */ boolean delete(People people); /** * * @method :delete<br> * @describe :根据ID删除用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:30:33 <br> * @param id * @return boolean */ boolean delete(long id); /** * * @method :update<br> * @describe :更新用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:30:47 <br> * @param people * @return boolean */ boolean update(People people); /** * * @method :findById<br> * @describe :根据ID查找用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:30:57 <br> * @param id * @return People */ People findById(long id); /** * * @method :findAll<br> * @describe :查找所有用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:31:24 <br> * @return List<People> */ List<People> findAll(); /** * * @method :findByCondition<br> * @describe :根据条件查找用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:31:40 <br> * @param condition * @return List<People> */ List<People> findByCondition(Map<String, Object> condition); /** * * @method :findAllNames<br> * @describe :根据key值,查找姓名<br> * @author :wanglongjie<br> * @createDate :2015年8月18日下午2:43:51 <br> * @param key * @return List<String> */ List<String> findAllNames(String key); }
/** * @package :example.crud.dao.impl<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:32:23<br> */ package example.crud.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.support.JdbcDaoSupport; import example.crud.dao.PeopleDao; import example.crud.entity.Gender; import example.crud.entity.People; import example.crud.util.MyTimesUtil; /** * @package :example.crud.dao.impl<br> * @file :PeopleDaoImpl.java<br> * @describe :用户Dao层接口实现类<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:32:23<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public class PeopleDaoImpl extends JdbcDaoSupport implements PeopleDao { /** * * @method :createOrQuerySequence<br> * @describe :创建或查询序列<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午9:43:17 <br> * @param seqName * @return int */ private int createOrQuerySequence(String seqName) { int querySequence = 1; try { String querySql = "select seq_" + seqName + ".nextval num from dual t"; querySequence = Integer.parseInt(getJdbcTemplate() .queryForMap(querySql).get("num").toString()); } catch (Exception e) { String creatSql = "create sequence seq_" + seqName + " minvalue 1 start with 1 increment by 1 cache 20"; getJdbcTemplate().execute(creatSql); } return querySequence; } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#save(example.crud.entity.People) */ @Override public boolean save(People people) { // TODO Auto-generated method stub String insert = "insert into people(id, name, age, birthday, gender, hobby) values (?,?,?,to_date(?,'yyyy-MM-dd'),?,?)"; Object[] obj = new Object[] { createOrQuerySequence(People.class.getSimpleName()), people.getName(), people.getAge(), MyTimesUtil.format(people.getBirthday()), people.getGender().toString(), people.getHobby() }; try { getJdbcTemplate().update(insert, obj); return true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return false; } } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#delete(example.crud.entity.People) */ @Override public boolean delete(People people) { // TODO Auto-generated method stub String delete = "delete from people t where t.id = ?"; try { getJdbcTemplate().update(delete, people.getId()); return true; } catch (Exception e) { // TODO: handle exception return false; } } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#delete(long) */ @Override public boolean delete(long id) { // TODO Auto-generated method stub String delete = "delete from people t where t.id = ?"; try { getJdbcTemplate().update(delete, id); return true; } catch (Exception e) { // TODO: handle exception return false; } } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#update(example.crud.entity.People) */ @Override public boolean update(People people) { // TODO Auto-generated method stub String update = "update people t set t.name = ?, t.age = ?, t.birthday = to_date(?,'yyyy-MM-dd'), t.gender = ?, t.hobby = ? where t.id = ?"; Object[] obj = new Object[] { people.getName(), people.getAge(), MyTimesUtil.format(people.getBirthday()), people.getGender().toString(), people.getHobby(), people.getId() }; try { getJdbcTemplate().update(update, obj); return true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return false; } } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#findById(long) */ @Override public People findById(long id) { // TODO Auto-generated method stub final People people = new People(); String find = "select * from people where id = '" + id + "'"; getJdbcTemplate().query(find, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { // TODO Auto-generated method stub do { people.setId(rs.getInt("id")); people.setName(rs.getString("name")); people.setAge(rs.getInt("age")); people.setBirthday(rs.getDate("birthday")); String sex = rs.getString("gender"); if (sex.equalsIgnoreCase("男")) { people.setGender(Gender.男); } else if (sex.equalsIgnoreCase("女")) { people.setGender(Gender.女); } people.setHobby(rs.getString("hobby")); } while (rs.next()); } }); return people; } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#findAll() */ @Override public List<People> findAll() { // TODO Auto-generated method stub final List<People> peoples = new ArrayList<>(); String find = "select * from people"; getJdbcTemplate().query(find, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { // TODO Auto-generated method stub do { People people = new People(); people.setId(rs.getInt("id")); people.setName(rs.getString("name")); people.setAge(rs.getInt("age")); people.setBirthday(rs.getDate("birthday")); String sex = rs.getString("gender"); if (sex.equalsIgnoreCase("男")) { people.setGender(Gender.男); } else if (sex.equalsIgnoreCase("女")) { people.setGender(Gender.女); } people.setHobby(rs.getString("hobby")); peoples.add(people); } while (rs.next()); } }); return peoples; } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#findByCondition(java.util.Map) */ @Override public List<People> findByCondition(Map<String, Object> condition) { // TODO Auto-generated method stub final List<People> peoples = new ArrayList<>(); StringBuffer find = new StringBuffer("select * from people"); if (!condition.isEmpty()) { find.append(" where "); Entry<String, Object> entry = null; String key = null; Object value = null; for (Iterator<Entry<String, Object>> it = condition.entrySet() .iterator(); it.hasNext();) { entry = it.next(); value = entry.getValue(); if (value != null && !value.equals("")) { key = entry.getKey(); if (key.equals("name")) { find.append(" name like '%" + value.toString().trim() + "%' and"); } else if (key.equals("gender")) { find.append(" upper(gender) = upper('" + value + "') and"); } else if (key.equals("hobby")) { find.append(" hobby like '%" + value.toString().trim() + "%' and"); } else if (key.equals("minage")) { find.append(" age >= '" + value + "' and"); } else if (key.equals("maxage")) { find.append(" age <= '" + value + "' and"); } else if (key.equals("minBirthday")) { find.append(" birthday >= to_date('" + value + "','yyyy-MM-dd') and"); } else if (key.equals("maxBirthday")) { find.append(" birthday <= to_date('" + value + "','yyyy-MM-dd') and"); } } } find.append(" 1=1"); } getJdbcTemplate().query(find.toString(), new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { // TODO Auto-generated method stub do { People people = new People(); people.setId(rs.getInt("id")); people.setName(rs.getString("name")); people.setAge(rs.getInt("age")); people.setBirthday(rs.getDate("birthday")); String sex = rs.getString("gender"); if (sex.equalsIgnoreCase("男")) { people.setGender(Gender.男); } else if (sex.equalsIgnoreCase("女")) { people.setGender(Gender.女); } people.setHobby(rs.getString("hobby")); peoples.add(people); } while (rs.next()); } }); return peoples; } /* * (non-Javadoc) * * @see example.crud.dao.PeopleDao#findAllNames(java.lang.String) */ @Override public List<String> findAllNames(String key) { // TODO Auto-generated method stub final List<String> list = new ArrayList<>(); String find = "select name from people"; if (key != null && !key.equals("")) { find += " where name like '%" + key + "%'"; } getJdbcTemplate().query(find, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { // TODO Auto-generated method stub do { list.add(rs.getString("name")); } while (rs.next()); } }); return list; } }4、将接口配置到Spring的Ioc容器,上篇的spring-service.xml已配置,也可采用Tapestry5专门配置服务的办法。
5、创建页面类,及页面模板:
首页面:Start.java
/** * @package :example.crud.pages<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午10:23:21<br> */ package example.crud.pages; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.tapestry5.Block; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.PropertyConduit; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.beaneditor.BeanModel; import org.apache.tapestry5.ioc.Messages; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.BeanModelSource; import example.crud.dao.PeopleDao; import example.crud.entity.People; import example.crud.entity.QueryPeople; import example.crud.pages.base.Base; /** * @package :example.crud.pages<br> * @file :Start.java<br> * @describe :<br> * @author :wanglongjie<br> * @createDate :2015年8月17日上午10:23:21<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public class Start extends Base { @Inject private Messages messages; @Inject private PeopleDao peopleDao; private List<People> peoples; @Property private People people; @Inject private Block viewBlock; @Property private People peopleOne; @Property private QueryPeople queryPeople = new QueryPeople(); List<String> onProvideCompletionsFromName(String key) { List<String> names = peopleDao.findAllNames(key); return names; } /** * * @method :getPeoples<br> * @describe :获取用户列表<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午1:40:34 <br> * @return List<People> */ public List<People> getPeoples() { if (queryPeople.getFlag().equals("") || queryPeople.getFlag() == null) peoples = peopleDao.findAll(); else { Map<String, Object> condition = new HashMap<>(); String gender = queryPeople.getGender() == null ? "" : queryPeople .getGender().toString(); condition.put("gender", gender); condition.put("minage", queryPeople.getMinAge()); condition.put("maxage", queryPeople.getMaxAge()); condition.put("minBirthday", queryPeople.getMinBirthday()); condition.put("maxBirthday", queryPeople.getMaxBirthday()); condition.put("name", queryPeople.getName()); condition.put("hobby", queryPeople.getHobby()); peoples = peopleDao.findByCondition(condition); } return peoples; } /** * * @method :onActionFromDelete<br> * @describe :删除用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午1:40:46 <br> * @param id * void */ void onActionFromDelete(long id) { peopleDao.delete(id); } /** * * @method :onActionFromView<br> * @describe :查找用户详细信息<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午3:34:52 <br> * @param id * @return Block */ Block onActionFromView(long id) { peopleOne = peopleDao.findById(id); return viewBlock; } /** * * @method :onSuccessFromQueryForm<br> * @describe :<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午3:38:37 <br> * void */ Object onSuccessFromQueryForm() { queryPeople.setFlag("query"); return Start.class; } // [用户实体模型 START] @Inject private BeanModelSource beanModelSource; @Inject private ComponentResources componentResources; private BeanModel<People> peopleBeanModel; public BeanModel<People> getPeopleBeanModel() { if (peopleBeanModel == null) { peopleBeanModel = beanModelSource.createEditModel(People.class, messages); peopleBeanModel.get("name").label("用户名"); peopleBeanModel.get("age").label("年龄"); peopleBeanModel.get("gender").label("性别"); peopleBeanModel.get("birthday").label("生日"); peopleBeanModel.get("hobby").label("兴趣爱好"); peopleBeanModel.add("view", new selfPropertyConduit()).label("详情"); peopleBeanModel.add("delete", new selfPropertyConduit()) .label("删除"); } return peopleBeanModel; } class selfPropertyConduit implements PropertyConduit { /* * (non-Javadoc) * * @see * org.apache.tapestry5.ioc.AnnotationProvider#getAnnotation(java.lang * .Class) */ @Override public <T extends Annotation> T getAnnotation(Class<T> arg0) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.apache.tapestry5.PropertyConduit#get(java.lang.Object) */ @Override public Object get(Object arg0) { // TODO Auto-generated method stub return ""; } /* * (non-Javadoc) * * @see org.apache.tapestry5.PropertyConduit#getPropertyType() */ @SuppressWarnings("rawtypes") @Override public Class getPropertyType() { // TODO Auto-generated method stub return String.class; } /* * (non-Javadoc) * * @see org.apache.tapestry5.PropertyConduit#set(java.lang.Object, * java.lang.Object) */ @Override public void set(Object arg0, Object arg1) { // TODO Auto-generated method stub } } // [用户实体模型 END] }首页面模板 Start.tml
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd"> <t:form t:id="queryForm" t:clientValidation="false"> <h2>检索用户</h2> <t:hidden value="queryPeople.flag"/> 性别: <t:select t:id="gender" model="genders" value="queryPeople.gender" style="margin-right:15px; width:80px;"/> 年龄: <t:textfield value="queryPeople.minAge" style="width:40px;" validate="min=0,max=100"/> ~ <t:textfield value="queryPeople.maxAge" style="margin-right:15px; width:40px;" validate="min=0,max=100"/> 生日: <t:textfield value="queryPeople.minBirthday" style="width:100px;" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"/> ~ <t:textfield value="queryPeople.maxBirthday" style="margin-right:15px;width:100px;" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"/> 姓名: <t:textfield t:id="name" value="queryPeople.name" t:mixins="autocomplete" style="margin-right:10px; width:120px;" /> 兴趣: <t:textfield t:id="queryHobby" value="queryPeople.hobby" style="margin-right:15px; width:120px;"/> <t:submit value="查询" style="width:100px"/> </t:form> <hr/> <t:grid source="peoples" row="people" model="peopleBeanModel" rowsPerPage="10"> <t:parameter name="nameCell"> <t:pagelink page="edit" context="people.id">${people.name}</t:pagelink> </t:parameter> <t:parameter name="viewCell"> <t:actionlink t:id="view" context="people.id" zone="viewZone">View</t:actionlink> </t:parameter> <t:parameter name="deleteCell"> <t:actionlink t:id="delete" context="people.id">Delete</t:actionlink> </t:parameter> </t:grid> <hr/> <t:zone t:id="viewZone" /> <t:block t:id="viewBlock"> <h2>【${peopleOne.name}】的资料</h2> <ul style="padding-left: 40px;"> <li>年龄: ${peopleOne.age}</li> <li>性别: ${peopleOne.gender}</li> <li>生日: ${peopleOne.birthday}</li> <li>兴趣: ${peopleOne.hobby}</li> </ul> </t:block> <t:pagelink page="edit" context="0">添加新用户</t:pagelink> </html>编辑页面:Edit.java
/** * @package :example.crud.pages<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午12:58:35<br> */ package example.crud.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import example.crud.dao.PeopleDao; import example.crud.entity.People; import example.crud.pages.base.Base; /** * @package :example.crud.pages<br> * @file :Edit.java<br> * @describe :更新用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午12:58:35<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ public class Edit extends Base { @Inject private PeopleDao peopleDao; @Property private People people = new People(); private long people_id; void onActivate(long id) { if (id > 0) { // 修改用户 people = peopleDao.findById(id); people_id = id; } } long onPassivate() { return people_id; } /** * * @method :onSuccess<br> * @describe :更新用户<br> * @author :wanglongjie<br> * @createDate :2015年8月17日下午2:41:32 <br> * @return Object */ Object onSuccess() { if (people_id > 0) { // 修改用户 peopleDao.update(people); } else { // 添加用户 peopleDao.save(people); } return Start.class; } }
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd"> <h2>编辑/创建 用户</h2> <t:form> <div> <t:label for="name"/> <t:textfield t:id="name" value="people.name" label="姓名:" validate="required,minlength=2,maxlength=6"/> </div> <div> <t:label for="age"/> <t:textfield t:id="age" value="people.age" label="年龄:" validate="required,min=0,max=100"/> </div> <div> <t:label for="birthday"/> <t:datefield t:id="birthday" value="people.birthday" label="生日:" format="yyyy-MM-dd" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"/> </div> <div> <t:label for="gender"/> <t:select t:id="gender" model="genders" value="people.gender" label="性别:"/> </div> <div> <t:label for="hobby"/> <t:textfield t:id="hobby" value="people.hobby" label="兴趣:"/> </div> <t:submit value="创建/更新"/> </t:form> <t:pagelink page="start">返回主页</t:pagelink> </html>
/** * @package :example.crud.pages.base<br> * @author :wanglongjie<br> * @createDate :2015年8月18日下午4:44:46<br> */ package example.crud.pages.base; import org.apache.tapestry5.SelectModel; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.ioc.Messages; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.util.EnumSelectModel; import example.crud.entity.Gender; /** * @package :example.crud.pages.base<br> * @file :Base.java<br> * @describe :<br> * @author :wanglongjie<br> * @createDate :2015年8月18日下午4:44:46<br> * @updater :<br> * @updateDate :<br> * @updateContent :<br> */ @Import(library = "context:js/My97DatePicker/WdatePicker.js") public class Base { @Inject private Messages messages; public SelectModel getGenders() { return new EnumSelectModel(Gender.class, messages); } public Gender getMale() { return Gender.男; } public Gender getFemale() { return Gender.女; } }