开始再看这个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玩玩看