struts2的demo中show case的crud示例
2007-05-09 10:51
232 查看
开始再看这个crud示例时,居然发现我没有准备数据库信息及数据也可以运行成功,后来看了实现才明白,该示例使用了Map模拟数据库存储操作数据,不过struts2的实现还是又可以观飨的地方,下面就看看它的实现。
首先,定义持久类存储接口Storage:
public interface Storage extends Serializable ...{
IdEntity get( Class entityClass, Serializable id );
Serializable create ( IdEntity object ) throws CreateException;
IdEntity update ( IdEntity object ) throws UpdateException;
Serializable merge ( IdEntity object ) throws StorageException;
int delete( Class entityClass, Serializable id ) throws CreateException;
int delete( IdEntity object ) throws CreateException;
Collection findAll( Class entityClass );
}
很明了,定义了操作数据的几种的方法,然后实现了一种使用map存储数据的方式(当然你可以使用自己存储数据的方式实现,比如xml等等)代码如下:
public class MemoryStorage implements Storage ...{
private static final long serialVersionUID = 8611213748834904125L;
private Map memory = new HashMap();
private Map getEntityMap ( Class entityClass ) ...{
if (entityClass != null) ...{
Map tryMap = (Map) memory.get(entityClass);
if (tryMap == null) ...{
synchronized(memory) ...{
tryMap = new HashMap();
memory.put(entityClass, tryMap);
}
}
return tryMap;
} else ...{
return null;
}
}
private IdEntity intStore( Class entityClass, IdEntity object ) ...{
getEntityMap(entityClass).put(object.getId(), object);
return object;
}
public IdEntity get( Class entityClass, Serializable id ) ...{
if (entityClass != null && id != null) ...{
return (IdEntity) getEntityMap(entityClass).get(id);
} else ...{
return null;
}
}
public Serializable create ( IdEntity object ) throws CreateException ...{
if (object == null) ...{
throw new CreateException("Either given class or object was null");
}
if (object.getId() == null) ...{
throw new CreateException("Cannot store object with null id");
}
if (get(object.getClass(), object.getId()) != null) ...{
throw new DuplicateKeyException("Object with this id already exists.");
}
return intStore(object.getClass(), object).getId();
}
public IdEntity update ( IdEntity object ) throws UpdateException ...{
if (object == null) ...{
throw new UpdateException("Cannot update null object.");
}
if ( get(object.getClass(), object.getId())==null ) ...{
throw new UpdateException("Object to update not found.");
}
return intStore(object.getClass(), object);
}
public Serializable merge ( IdEntity object ) throws StorageException ...{
if (object == null) ...{
throw new StorageException("Cannot merge null object");
}
if (object.getId() == null || get(object.getClass(), object.getId())==null) ...{
return create(object);
} else ...{
return update(object).getId();
}
}
public int delete( Class entityClass, Serializable id ) throws CreateException ...{
try ...{
if (get(entityClass, id) != null) ...{
getEntityMap(entityClass).remove(id);
return 1;
} else ...{
return 0;
}
} catch (Exception e) ...{
throw new CreateException(e);
}
}
public int delete( IdEntity object ) throws CreateException ...{
if (object == null) ...{
throw new CreateException("Cannot delete null object");
}
return delete(object.getClass(), object.getId());
}
public Collection findAll( Class entityClass ) ...{
if (entityClass != null) ...{
return getEntityMap(entityClass).values();
} else ...{
return new ArrayList();
}
}
public void reset() ...{
this.memory = new HashMap();
}
}
其实就是map操作数据的几种方式(get,put...)
这样一种不使用数据库存储数据的方式就已经算完成了,不过我们需要初始几个数据怎么实现呢?struts2使用了spring的 InitializingBean 接口[Spirng的InitializingBean为bean提供了定义初始化方法的方式。InitializingBean是一个接口,它仅仅包含一个方法:afterPropertiesSet()。]代码如下:
public class TestDataProvider implements Serializable, InitializingBean ...{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(TestDataProvider.class);
public static final String[] POSITIONS = ...{
"Developer",
"System Architect",
"Sales Manager",
"CEO"
};
public static final String[] LEVELS = ...{
"Junior",
"Senior",
"Master"
};
private static final Skill[] TEST_SKILLS = ...{
new Skill("WW-SEN", "Struts Senior Developer"),
new Skill("WW-JUN", "Struts Junior Developer"),
new Skill("SPRING-DEV", "Spring Developer")
};
public static final Employee[] TEST_EMPLOYEES = ...{
new Employee(new Long(1), "Alan", "Smithee", new Date(), new Float(2000f), true, POSITIONS[0],
TEST_SKILLS[0], null, "alan", LEVELS[0], "Nice guy"),
new Employee(new Long(2), "Robert", "Robson", new Date(), new Float(10000f), false, POSITIONS[1],
TEST_SKILLS[1], Arrays.asList(TEST_SKILLS).subList(1,TEST_SKILLS.length), "rob", LEVELS[1], "Smart guy")
};
private SkillDao skillDao;
private EmployeeDao employeeDao;
public void setSkillDao(SkillDao skillDao) ...{
this.skillDao = skillDao;
}
public void setEmployeeDao(EmployeeDao employeeDao) ...{
this.employeeDao = employeeDao;
}
protected void addTestSkills() ...{
try ...{
for (int i = 0, j = TEST_SKILLS.length; i < j; i++) ...{
skillDao.merge(TEST_SKILLS[i]);
}
if (log.isInfoEnabled()) ...{
log.info("TestDataProvider - [addTestSkills]: Added test skill data.");
}
} catch (StorageException e) ...{
log.error("TestDataProvider - [addTestSkills]: Exception catched: " + e.getMessage());
}
}
protected void addTestEmployees() ...{
try ...{
for (int i = 0, j = TEST_EMPLOYEES.length; i < j; i++) ...{
employeeDao.merge(TEST_EMPLOYEES[i]);
}
if (log.isInfoEnabled()) ...{
log.info("TestDataProvider - [addTestEmployees]: Added test employee data.");
}
} catch (StorageException e) ...{
log.error("TestDataProvider - [addTestEmployees]: Exception catched: " + e.getMessage());
}
}
protected void addTestData() ...{
addTestSkills();
addTestEmployees();
}
public void afterPropertiesSet() throws Exception ...{
addTestData();
}
}
注意真正实现初始化的是afterPropertiesSet() 方法,当然要起效,还需要设定spring的配置文件,设定该部分配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="byName">
<bean id="storage" class="org.apache.struts2.showcase.application.MemoryStorage" singleton="true"/>
<bean id="testDataProvider" class="org.apache.struts2.showcase.application.TestDataProvider" singleton="true" lazy-init="false"/>
<bean id="skillDao" class="org.apache.struts2.showcase.dao.SkillDao"/>
<bean id="employeeDao" class="org.apache.struts2.showcase.dao.EmployeeDao"/>
最后在web.xml文件配置spring的监听器就ok了,现在启动web服务器,TestDataProvider 就会为持久类进行相应的数据初始化。
后记:如果大家比较感兴趣,可以使用xml代替map玩玩看
首先,定义持久类存储接口Storage:
public interface Storage extends Serializable ...{
IdEntity get( Class entityClass, Serializable id );
Serializable create ( IdEntity object ) throws CreateException;
IdEntity update ( IdEntity object ) throws UpdateException;
Serializable merge ( IdEntity object ) throws StorageException;
int delete( Class entityClass, Serializable id ) throws CreateException;
int delete( IdEntity object ) throws CreateException;
Collection findAll( Class entityClass );
}
很明了,定义了操作数据的几种的方法,然后实现了一种使用map存储数据的方式(当然你可以使用自己存储数据的方式实现,比如xml等等)代码如下:
public class MemoryStorage implements Storage ...{
private static final long serialVersionUID = 8611213748834904125L;
private Map memory = new HashMap();
private Map getEntityMap ( Class entityClass ) ...{
if (entityClass != null) ...{
Map tryMap = (Map) memory.get(entityClass);
if (tryMap == null) ...{
synchronized(memory) ...{
tryMap = new HashMap();
memory.put(entityClass, tryMap);
}
}
return tryMap;
} else ...{
return null;
}
}
private IdEntity intStore( Class entityClass, IdEntity object ) ...{
getEntityMap(entityClass).put(object.getId(), object);
return object;
}
public IdEntity get( Class entityClass, Serializable id ) ...{
if (entityClass != null && id != null) ...{
return (IdEntity) getEntityMap(entityClass).get(id);
} else ...{
return null;
}
}
public Serializable create ( IdEntity object ) throws CreateException ...{
if (object == null) ...{
throw new CreateException("Either given class or object was null");
}
if (object.getId() == null) ...{
throw new CreateException("Cannot store object with null id");
}
if (get(object.getClass(), object.getId()) != null) ...{
throw new DuplicateKeyException("Object with this id already exists.");
}
return intStore(object.getClass(), object).getId();
}
public IdEntity update ( IdEntity object ) throws UpdateException ...{
if (object == null) ...{
throw new UpdateException("Cannot update null object.");
}
if ( get(object.getClass(), object.getId())==null ) ...{
throw new UpdateException("Object to update not found.");
}
return intStore(object.getClass(), object);
}
public Serializable merge ( IdEntity object ) throws StorageException ...{
if (object == null) ...{
throw new StorageException("Cannot merge null object");
}
if (object.getId() == null || get(object.getClass(), object.getId())==null) ...{
return create(object);
} else ...{
return update(object).getId();
}
}
public int delete( Class entityClass, Serializable id ) throws CreateException ...{
try ...{
if (get(entityClass, id) != null) ...{
getEntityMap(entityClass).remove(id);
return 1;
} else ...{
return 0;
}
} catch (Exception e) ...{
throw new CreateException(e);
}
}
public int delete( IdEntity object ) throws CreateException ...{
if (object == null) ...{
throw new CreateException("Cannot delete null object");
}
return delete(object.getClass(), object.getId());
}
public Collection findAll( Class entityClass ) ...{
if (entityClass != null) ...{
return getEntityMap(entityClass).values();
} else ...{
return new ArrayList();
}
}
public void reset() ...{
this.memory = new HashMap();
}
}
其实就是map操作数据的几种方式(get,put...)
这样一种不使用数据库存储数据的方式就已经算完成了,不过我们需要初始几个数据怎么实现呢?struts2使用了spring的 InitializingBean 接口[Spirng的InitializingBean为bean提供了定义初始化方法的方式。InitializingBean是一个接口,它仅仅包含一个方法:afterPropertiesSet()。]代码如下:
public class TestDataProvider implements Serializable, InitializingBean ...{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(TestDataProvider.class);
public static final String[] POSITIONS = ...{
"Developer",
"System Architect",
"Sales Manager",
"CEO"
};
public static final String[] LEVELS = ...{
"Junior",
"Senior",
"Master"
};
private static final Skill[] TEST_SKILLS = ...{
new Skill("WW-SEN", "Struts Senior Developer"),
new Skill("WW-JUN", "Struts Junior Developer"),
new Skill("SPRING-DEV", "Spring Developer")
};
public static final Employee[] TEST_EMPLOYEES = ...{
new Employee(new Long(1), "Alan", "Smithee", new Date(), new Float(2000f), true, POSITIONS[0],
TEST_SKILLS[0], null, "alan", LEVELS[0], "Nice guy"),
new Employee(new Long(2), "Robert", "Robson", new Date(), new Float(10000f), false, POSITIONS[1],
TEST_SKILLS[1], Arrays.asList(TEST_SKILLS).subList(1,TEST_SKILLS.length), "rob", LEVELS[1], "Smart guy")
};
private SkillDao skillDao;
private EmployeeDao employeeDao;
public void setSkillDao(SkillDao skillDao) ...{
this.skillDao = skillDao;
}
public void setEmployeeDao(EmployeeDao employeeDao) ...{
this.employeeDao = employeeDao;
}
protected void addTestSkills() ...{
try ...{
for (int i = 0, j = TEST_SKILLS.length; i < j; i++) ...{
skillDao.merge(TEST_SKILLS[i]);
}
if (log.isInfoEnabled()) ...{
log.info("TestDataProvider - [addTestSkills]: Added test skill data.");
}
} catch (StorageException e) ...{
log.error("TestDataProvider - [addTestSkills]: Exception catched: " + e.getMessage());
}
}
protected void addTestEmployees() ...{
try ...{
for (int i = 0, j = TEST_EMPLOYEES.length; i < j; i++) ...{
employeeDao.merge(TEST_EMPLOYEES[i]);
}
if (log.isInfoEnabled()) ...{
log.info("TestDataProvider - [addTestEmployees]: Added test employee data.");
}
} catch (StorageException e) ...{
log.error("TestDataProvider - [addTestEmployees]: Exception catched: " + e.getMessage());
}
}
protected void addTestData() ...{
addTestSkills();
addTestEmployees();
}
public void afterPropertiesSet() throws Exception ...{
addTestData();
}
}
注意真正实现初始化的是afterPropertiesSet() 方法,当然要起效,还需要设定spring的配置文件,设定该部分配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="byName">
<bean id="storage" class="org.apache.struts2.showcase.application.MemoryStorage" singleton="true"/>
<bean id="testDataProvider" class="org.apache.struts2.showcase.application.TestDataProvider" singleton="true" lazy-init="false"/>
<bean id="skillDao" class="org.apache.struts2.showcase.dao.SkillDao"/>
<bean id="employeeDao" class="org.apache.struts2.showcase.dao.EmployeeDao"/>
最后在web.xml文件配置spring的监听器就ok了,现在启动web服务器,TestDataProvider 就会为持久类进行相应的数据初始化。
后记:如果大家比较感兴趣,可以使用xml代替map玩玩看
相关文章推荐
- Spring4-Struts2-Hibernate4 CRUD Demo
- struts2入门Demo示例
- struts2入门Demo示例
- jQuery prototype冲突的2种解决方法(附demo示例下载)
- Struts2系列:(36)struts2 UI tag示例
- Struts2获取演示示例教程
- struts2 demo 含例子
- js实现的页面加载完毕之前loading提示效果完整示例【附demo源码下载】
- struts2(2)---入门示例
- Struts2登陆的Demo
- 【java开发系列】—— struts2简单入门示例
- Spring MVC实现一次简单的CRUD示例
- http发送json格式数据请求 demo示例
- 学习React中ref的两个demo示例
- Struts2中是用拦截器拦截黑名单的demo
- JSON+AJAX+STRUTS2操作页面表格示例
- Struts2 自定义类型转换器的简单示例
- Struts2上传文件示例 【转】
- 普元 EOS Platform 7.6 从表主键生成策略采用:自动生成uuid,实现主从表增删改查示例demo
- java webservices 接口示例和demo下载地址