概述:基于struts2.23 + spring2.5.6 + hibernate3.6.4 + hibernate-generic-dao1.0(除了spring,我整合的都是最新的GA包,hibernate-generic-dao是google项目库中一个开源的basedao,我灰常喜欢,因为我找不到更好更适合我的)

 

项目代码是基于eclipse3.6创建的,很简单,大家直接导入则可运行。

 

1.包结构,源码,测试用例,配置文件一目了然。每个功能模块都在modules包下做开发,配置文件统一在resource管理(基实也没多少配置文件,都用注解嘛)。

 

 

2.无论阅读哪个web项目代码,我都是先从web.xml开始,项目有什么东西一清二楚。

我这里将log4j监听放在第一,我想他应该能够从系统启动开启就能记录我的所有日志(求认证)。第二个监听是proxool数据库连接池,听说很高效,所以果断引入(引入步骤搞得复杂吧,我还重写了监听。一切为了稳定,也好扩展我某日喜欢加入动态切换数据源做准备。呵呵)。OpenSessionInView,我想如果你不喜欢可以摘掉,反正我很喜欢。Struts2指定了自定义的struts.xml文件位置,指定扫描注解的action路径。最后是proxool的可视化图形监控,很棒。
001    <?xml version="1.0" encoding="UTF-8"?>
002    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
003        xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
004        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
005        id="WebApp_ID" version="2.5">
006        <display-name>framework</display-name>
007        <context-param>
008            <param-name>log4jConfigLocation</param-name>
009            <param-value>/WEB-INF/classes/resources/log4j/log4j.properties</param-value>
010        </context-param>
011        <context-param>
012            <param-name>propertyFile</param-name>
013            <param-value>/WEB-INF/classes/resources/hibernate/proxool.properties</param-value>
014        </context-param>
015        <context-param>
016            <param-name>contextConfigLocation</param-name>
017            <param-value>classpath:resources/spring/applicationContext.xml</param-value>
018        </context-param>
019        <!-- log4j Listener -->
020        <listener>
021            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
022        </listener>
023        <!-- Proxool Listener -->
024        <listener>
025            <listener-class>org.chinasb.framework.core.db.ProxoolListener</listener-class>
026        </listener>
027        <!-- Open Session In View Filter -->
028        <filter>
029            <filter-name>OpenSessionInViewFilter</filter-name>
030            <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
031            <init-param>
032                <param-name>singleSession</param-name>
033                <param-value>true</param-value>
034            </init-param>
035        </filter>
036        <filter-mapping>
037            <filter-name>OpenSessionInViewFilter</filter-name>
038            <url-pattern>/*</url-pattern>
039        </filter-mapping>
040        <!-- Spring Listener -->
041        <listener>
042            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
043        </listener>
044        <!-- Character Encoding Filter -->
045        <filter>
046            <filter-name>Set Character Encoding</filter-name>
047            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
048            <init-param>
049                <param-name>encoding</param-name>
050                <param-value>UTF-8</param-value>
051            </init-param>
052            <init-param>
053                <param-name>forceEncoding</param-name>
054                <!-- 强制进行转码 -->
055                <param-value>true</param-value>
056            </init-param>
057        </filter>
058        <filter-mapping>
059            <filter-name>Set Character Encoding</filter-name>
060            <url-pattern>/*</url-pattern>
061        </filter-mapping>
062        <!-- 延长action中属性的生命周期, -->
063        <filter>
064            <filter-name>struts-cleanup</filter-name>
065            <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
066        </filter>
067        <filter-mapping>
068            <filter-name>struts-cleanup</filter-name>
069            <url-pattern>/*</url-pattern>
070        </filter-mapping>
071        <!-- Struts2 Filter -->
072        <filter>
073            <filter-name>struts2</filter-name>
074            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
075            <init-param>
076                <param-name>config</param-name>
077                <param-value>struts-default.xml,struts-plugin.xml,resources/struts/struts.xml</param-value>
078            </init-param>
079            <init-param>
080                <param-name>actionPackages</param-name>
081                <param-value>org.chinasb.framework.modules</param-value>
082            </init-param>
083        </filter>
084        <filter-mapping>
085            <filter-name>struts2</filter-name>
086            <url-pattern>/*</url-pattern>
087        </filter-mapping>
088        <!-- Proxool Monitoring -->
089        <servlet>
090            <servlet-name>Admin</servlet-name>
091            <servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
092        </servlet>
093        <servlet-mapping>
094            <servlet-name>Admin</servlet-name>
095            <url-pattern>/admin.html</url-pattern>
096        </servlet-mapping>
097        <!-- Welcome List -->
098        <welcome-file-list>
099            <welcome-file>index.html</welcome-file>
100            <welcome-file>index.htm</welcome-file>
101            <welcome-file>index.jsp</welcome-file>
102        </welcome-file-list>
103    </web-app>

3.applicationContext.xml,我想下面注释得也比较清楚了,如果我写错了或理解错了希望指正。
01    <?xml version="1.0" encoding="UTF-8"?>
02    <beans xmlns="http://www.springframework.org/schema/beans"
03        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04        xmlns:context="http://www.springframework.org/schema/context"
05        xsi:schemaLocation="
06    
07    http://www.springframework.org/schema/beans
08    
09    
10    http://www.springframework.org/schema/beans/spring-beans.xsd
11    
12    
13    http://www.springframework.org/schema/context
14    
15    
16    http://www.springframework.org/schema/context/spring-context.xsd">
17    
18        <!-- 使用 annotation -->
19        <context:annotation-config />
20    
21        <!-- 使用 annotation 自动注册bean,并检查@Controller, @Service, @Repository注解已被注入 -->
22        <context:component-scan base-package="org.chinasb.framework.modules" />
23    
24        <!-- hibernate属性配置 -->
25        <context:property-placeholder location="classpath:resources/hibernate/hibernate.properties"/>
26    
27        <!-- Hibernate 配置管理 -->
28        <import resource="applicationContext-persistence.xml" />
29    
30    </beans>

4.hiberante配置所需的一些属性,指定方言,开始hibernate缓存等,后面还有一个c3p0的数据连接池属性。你们下载的代码里面,数据源方面我换成了c3p0,因为proxool我配置的是随web启动的,而我又不想改成随spring加载启动。所以我开发中注释掉proxool,以后上线再打开。
01    ## hibernate
02    hibernate.dialect=org.hibernate.dialect.MySQLDialect
03    hibernate.show_sql=true
04    hibernate.format_sql=false
05    hibernate.hbm2ddl.auto=update
06    
07    ## hibernate cache
08    hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
09    hibernate.cache.use_query_cache=false
10    hibernate.cache.use_second_level_cache=true
11    
12    ## C3P0 configuration
13    hibernate.connection.driver_class=com.mysql.jdbc.Driver
14    hibernate.connection.url=jdbc:mysql://localhost:3306/chinasb??useUnicode=true&characterEncoding=utf-8
15    hibernate.connection.username=root
16    hibernate.connection.password=root

5.applicationContext-persistence.xml,这里就是数据源及事务的一些配置了。事务我使用了cglib类级别的代理注解配置方式,如果你喜欢用jdk接口方式动态的代理,可以去掉 proxy-target-class="true"。顺便也保留了声名式事务。
001    <?xml version="1.0" encoding="UTF-8"?>
002    <beans xmlns="http://www.springframework.org/schema/beans"
003        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
004        xmlns:context="http://www.springframework.org/schema/context"
005        xmlns:aop="http://www.springframework.org/schema/aop"
006        xmlns:tx="http://www.springframework.org/schema/tx"
007        xsi:schemaLocation="
008    
009    http://www.springframework.org/schema/beans
010    
011    
012    http://www.springframework.org/schema/beans/spring-beans.xsd
013    
014    
015    http://www.springframework.org/schema/context
016    
017    
018    http://www.springframework.org/schema/context/spring-context.xsd
019    
020    
021    http://www.springframework.org/schema/aop
022    
023    
024    http://www.springframework.org/schema/aop/spring-aop.xsd
025    
026    
027    http://www.springframework.org/schema/tx
028    
029    
030    http://www.springframework.org/schema/tx/spring-tx.xsd">
031    
032        <!-- Proxool 数据源 -->
033        <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
034            <property name="driverClassName">
035                <value>org.logicalcobwebs.proxool.ProxoolDriver</value>
036            </property>
037            <property name="url">
038                <value>proxool.default</value>
039            </property>
040        </bean> -->
041    
042        <!-- C3P0 数据源 -->
043        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
044            <property name="driverClass" value="${hibernate.connection.driver_class}"/>
045            <property name="jdbcUrl" value="${hibernate.connection.url}"/>
046            <property name="properties">
047                <props>
048                    <prop key="user">${hibernate.connection.username}</prop>
049                    <prop key="password">${hibernate.connection.password}</prop>
050                </props>
051            </property>
052        </bean>
053    
054        <!-- SessionFactory -->
055        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
056            <property name="dataSource" ref="dataSource" />
057            <property name="packagesToScan" value="org.chinasb.framework.modules.*.model"/>
058            <property name="hibernateProperties">
059                <props>
060                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
061                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
062                    <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
063                    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
064                    <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
065                    <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
066                    <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
067                </props>
068            </property>
069        </bean>
070    
071        <!-- 配置事务管理 -->
072        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
073            <property name="sessionFactory" ref="sessionFactory" />
074        </bean>
075    
076        <!-- 配置注解实现管理事务(cglib:proxy-target-class="true") -->
077        <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
078    
079        <!-- 指定使用cglib -->
080        <!-- <aop:aspectj-autoproxy proxy-target-class="true" />  -->
081    
082        <!-- 配置事务的传播特性 -->
083        <!--
084        <tx:advice id="txAdvice" transaction-manager="transactionManager">
085            <tx:attributes>
086                <tx:method name="add*" propagation="REQUIRED" />
087                <tx:method name="edit*" propagation="REQUIRED" />
088                <tx:method name="remove*" propagation="REQUIRED" />
089                <tx:method name="save*" propagation="REQUIRED" />
090                <tx:method name="update*" propagation="REQUIRED" />
091                <tx:method name="delete*" propagation="REQUIRED" />
092                <tx:method name="batchUpdate" propagation="REQUIRED" />
093                <tx:method name="*" read-only="true" />
094            </tx:attributes>
095        </tx:advice>
096        -->
097    
098        <!-- 配置事务的切入点 -->
099        <!--
100        <aop:config>
101            <aop:pointcut id="targetMethod" expression="execution(* org.chinasb.framework.modules..service.*.*(..))" />
102            <aop:advisor advice-ref="txAdvice" pointcut-ref="targetMethod" />
103        </aop:config>
104        -->
105    
106    </beans>

6.struts.xml,你懂的。
01    <?xml version="1.0" encoding="UTF-8"?>
02    <!DOCTYPE struts PUBLIC
03        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
04        "http://struts.apache.org/dtds/struts-2.0.dtd">
05    
06    <struts>
07        <!-- 开启使用开发模式,详细错误提示 -->
08        <constant name="struts.devMode" value="false" />
09        <!-- 将对象交给spring管理 -->
10        <constant name="struts.objectFactory" value="spring" />
11        <!-- 指定资源编码类型 -->
12        <constant name="struts.i18n.encoding" value="UTF-8" />
13        <!-- 指定每次请求到达,重新加载资源文件 -->
14        <constant name="struts.i18n.reload" value="false" />
15        <!-- 指定每次配置文件更改后,自动重新加载 -->
16        <constant name="struts.configuration.xml.reload" value="false" />
17        <!-- 国际化资源文件 -->
18        <constant name="struts.custom.i18n.resources" value="resources/content/Language" />
19        <!-- 默认后缀名 -->
20        <constant name="struts.action.extension" value="do,action,jhtml,," />
21        <!-- Struts Annotation -->
22        <constant name="actionPackages" value="org.chinasb.framework.modules"/>
23    </struts>

好了,下面我简单讲一下开发流程。

 

在modules下建立模块,和相应的包(action,dao,model,service,util),比如我上面包结构的demo模块。

 

demo.java,model类,映射数据库中的表,每个model一张表,为了适应basedao,每个model还对应每个dao(不要觉得这是麻烦的)。jpa的注解,你们懂的,不解释。
01    package org.chinasb.framework.modules.demo.model;
02    
03    import java.io.Serializable;
04    import java.util.Date;
05    
06    import javax.persistence.Entity;
07    import javax.persistence.GeneratedValue;
08    import javax.persistence.GenerationType;
09    import javax.persistence.Id;
10    
11    import org.hibernate.annotations.Cache;
12    import org.hibernate.annotations.CacheConcurrencyStrategy;
13    
14    @Entity
15    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
16    public class Demo implements Serializable {
17        private static final long serialVersionUID = 1L;
18    
19        @Id
20        @GeneratedValue(strategy = GenerationType.AUTO)
21        private int id;
22        private String title;
23        private String content;
24        private Date publishdate;
25    
26        public int getId() {
27        return id;
28        }
29    
30        public void setId(int id) {
31        this.id = id;
32        }
33    
34        public String getTitle() {
35        return title;
36        }
37    
38        public void setTitle(String title) {
39        this.title = title;
40        }
41    
42        public String getContent() {
43        return content;
44        }
45    
46        public void setContent(String content) {
47        this.content = content;
48        }
49    
50        public Date getPublishdate() {
51        return publishdate;
52        }
53    
54        public void setPublishdate(Date publishdate) {
55        this.publishdate = publishdate;
56        }
57    
58    }

DemoDao,接口类。我想在多数程序员的项目里做的绝大多数事情都是相关数据库的CURD操作,所以基础框架里整合一个强大的BaseDao是必须的,而我选择了开源的GenericDao(觉得不适合你的可以替掉)。直接继承GenericDao接口,指定操作的model,与主键的类型。
1    package org.chinasb.framework.modules.demo.dao;
2    
3    import org.chinasb.framework.core.base.dao.hibernate.GenericDAO;
4    import org.chinasb.framework.modules.demo.model.Demo;
5    
6    public interface DemoDao extends GenericDAO<Demo, Integer> {
7    
8    }

DemoDaoImpl,呵,这样写我觉得不麻烦,不多说。@Repository注解交给spring管理。
01    package org.chinasb.framework.modules.demo.dao.impl;
02    
03    import org.chinasb.framework.core.base.dao.BaseDAO;
04    import org.chinasb.framework.modules.demo.dao.DemoDao;
05    import org.chinasb.framework.modules.demo.model.Demo;
06    import org.springframework.stereotype.Repository;
07    
08    @Repository
09    public class DemoDaoImpl extends BaseDAO<Demo, Integer> implements DemoDao {
10    
11    }

BaseDAO,主要是注入sessionFactory给hibernate-generic-dao。
01    package org.chinasb.framework.core.base.dao;
02    
03    import java.io.Serializable;
04    
05    import org.chinasb.framework.core.base.dao.hibernate.GenericDAOImpl;
06    import org.hibernate.SessionFactory;
07    import org.springframework.beans.factory.annotation.Autowired;
08    
09    public class BaseDAO<T, ID extends Serializable> extends GenericDAOImpl<T, ID> {
10    
11        @Autowired
12        @Override
13        public void setSessionFactory(SessionFactory sessionFactory) {
14        super.setSessionFactory(sessionFactory);
15        }
16    }

DemoService,接下来就要定义一些相关数据库操作的业务接口给上层使用了,这里主要列出了baseDao能操作的部分,像分页,字段过滤查询方面的没有列出。
01    package org.chinasb.framework.modules.demo.service;
02    
03    import java.util.List;
04    import org.chinasb.framework.modules.demo.model.Demo;
05    
06    public interface DemoService {
07        /**
08         * 增加或更新demo
09         *
10         * @param demo
11         * @return
12         */
13        public boolean save(Demo demo);
14    
15        /**
16         * 批量增加或更新demo
17         *
18         * @param demo
19         * @return
20         */
21        public boolean[] save(Demo[] demos);
22    
23        /**
24         * 删除demo
25         *
26         * @param demo
27         * @return
28         */
29        public boolean remove(Demo demo);
30    
31        /**
32         * 批量删除demo
33         *
34         * @param demos
35         */
36        public void remove(Demo[] demos);
37    
38        /**
39         * 根据主键删除demo
40         *
41         * @param id
42         * @return
43         */
44        public boolean removeById(Integer id);
45    
46        /**
47         * 批量根据主键删除demo
48         *
49         * @param ids
50         */
51        public void removeByIds(Integer[] ids);
52    
53        /**
54         * 查询demo数据记录集
55         *
56         * @return
57         */
58        public List<Demo> findAll();
59    
60        /**
61         * 根据主键查询demo
62         *
63         * @param id
64         * @return
65         */
66        public Demo findById(Integer id);
67    
68        /**
69         * 批量根据主键查询demo记录集
70         *
71         * @param ids
72         * @return
73         */
74        public Demo[] findByIds(Integer[] ids);
75    
76        /**
77         * 持久化session数据到数据库
78         */
79        public void flush();
80    }

DemoServiceImpl,接口实现。这里全用注解控制了事务,及演示如何使用baseDao。当然强大的baseDao并不仅仅这些方法,还有分页等强大的查询数据功能。大家可以在http://code.google.com/p/hibernate-generic-dao/ 进行查看。
01    package org.chinasb.framework.modules.demo.service.impl;
02    
03    import java.util.List;
04    
05    import javax.annotation.Resource;
06    
07    import org.chinasb.framework.modules.demo.dao.DemoDao;
08    import org.chinasb.framework.modules.demo.model.Demo;
09    import org.chinasb.framework.modules.demo.service.DemoService;
10    import org.springframework.stereotype.Service;
11    import org.springframework.transaction.annotation.Propagation;
12    import org.springframework.transaction.annotation.Transactional;
13    
14    @Service
15    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
16    public class DemoServiceImpl implements DemoService {
17        @Resource
18        private DemoDao demoDao;
19    
20        @Override
21        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
22        public boolean save(Demo demo) {
23        return demoDao.save(demo);
24        }
25    
26        @Override
27        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
28        public boolean[] save(Demo[] demos) {
29        return demoDao.save(demos);
30        }
31    
32        @Override
33        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
34        public boolean remove(Demo demo) {
35        return demoDao.remove(demo);
36        }
37    
38        @Override
39        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
40        public void remove(Demo[] demos) {
41        demoDao.remove(demos);
42        }
43    
44        @Override
45        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
46        public boolean removeById(Integer id) {
47        return demoDao.removeById(id);
48        }
49    
50        @Override
51        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
52        public void removeByIds(Integer[] ids) {
53        demoDao.removeByIds(ids);
54        }
55    
56        @Override
57        public List<Demo> findAll() {
58        return demoDao.findAll();
59        }
60    
61        @Override
62        public Demo findById(Integer id) {
63        return demoDao.find(id);
64        }
65    
66        @Override
67        public Demo[] findByIds(Integer[] ids) {
68        return demoDao.find(ids);
69        }
70    
71        @Override
72        public void flush() {
73        demoDao.flush();
74        }
75    }

DemoAction,这里演示了查看,增,删功能。也是基于注解的方式,继承了baseAction。
01    package org.chinasb.framework.modules.demo.action;
02    
03    import java.util.Date;
04    import java.util.List;
05    
06    import javax.annotation.Resource;
07    
08    import org.apache.struts2.convention.annotation.Action;
09    import org.apache.struts2.convention.annotation.Result;
10    import org.chinasb.framework.core.base.action.BaseAction;
11    import org.chinasb.framework.modules.demo.model.Demo;
12    import org.chinasb.framework.modules.demo.service.DemoService;
13    import org.springframework.stereotype.Controller;
14    
15    @Controller
16    public class DemoAction extends BaseAction {
17    
18        private static final long serialVersionUID = 1L;
19    
20        @Resource
21        private DemoService demoService;
22    
23        @Action(value = "/demoAction", results = { @Result(name = SUCCESS, location = "/manager/modules/demo/index.jsp") })
24        @Override
25        public String execute() {
26        List<Demo> demoList = demoService.findAll();
27        httpServletRequest.setAttribute("DEMO_LIST", demoList);
28        return SUCCESS;
29        }
30    
31        @Action(value = "/demoAddAction", results = { @Result(name = SUCCESS, location = "/demoAction", type = "redirect") })
32        public String add() {
33        Demo demo = new Demo();
34        demo.setTitle(httpServletRequest.getParameter("title"));
35        demo.setContent(httpServletRequest.getParameter("content"));
36        demo.setPublishdate(new Date());
37        demoService.save(demo);
38        return SUCCESS;
39        }
40    
41        @Action(value = "/demoDeleteAction", results = { @Result(name = SUCCESS, location = "/demoAction", type = "redirect") })
42        public String delete() {
43        demoService.removeById(Integer.parseInt(httpServletRequest.getParameter("id")));
44        return SUCCESS;
45        }
46    }

 BaseAction,这里只封装了基本的request,reponse,context,session,大家按需要继续完善。
01    package org.chinasb.framework.core.base.action;
02    
03    import java.util.Map;
04    
05    import javax.servlet.ServletContext;
06    import javax.servlet.http.HttpServletRequest;
07    import javax.servlet.http.HttpServletResponse;
08    import javax.servlet.http.HttpSession;
09    
10    import org.apache.struts2.interceptor.ServletRequestAware;
11    import org.apache.struts2.interceptor.ServletResponseAware;
12    import org.apache.struts2.interceptor.SessionAware;
13    import org.apache.struts2.util.ServletContextAware;
14    
15    import com.opensymphony.xwork2.ActionSupport;
16    
17    public class BaseAction extends ActionSupport implements ServletContextAware,
18        ServletResponseAware, ServletRequestAware, SessionAware {
19    
20        private static final long serialVersionUID = 1L;
21    
22        protected ServletContext servletContext;
23    
24        protected HttpServletRequest httpServletRequest;
25    
26        protected HttpServletResponse httpServletResponse;
27    
28        protected HttpSession httpSession;
29    
30        protected Map<String, Object> session;
31    
32        @Override
33        public void setServletContext(ServletContext context) {
34        this.servletContext = context;
35        }
36    
37        @Override
38        public void setServletResponse(HttpServletResponse response) {
39        this.httpServletResponse = response;
40        }
41    
42        @Override
43        public void setServletRequest(HttpServletRequest request) {
44        this.httpServletRequest = request;
45        this.httpSession = request.getSession();
46        }
47    
48        @Override
49        public void setSession(Map<String, Object> session) {
50        this.session = session;
51        }
52    
53    }

最后就是测试用例了,这里使用了经典的junit4.4版本,依然是注解方式。

BaseTestTemplate,大家都不想每个用例都去写一次读取applicationContext吧,把一些公用的东西封装起来吧。
01    package org.chinasb.framework.core.base.test;
02    
03    import org.junit.runner.RunWith;
04    import org.springframework.test.context.ContextConfiguration;
05    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
06    import org.springframework.test.context.transaction.TransactionConfiguration;
07    import org.springframework.transaction.annotation.Propagation;
08    import org.springframework.transaction.annotation.Transactional;
09    
10    @RunWith(SpringJUnit4ClassRunner.class)
11    @ContextConfiguration(locations = { "classpath:resources/spring/applicationContext.xml" })
12    @TransactionConfiguration(defaultRollback = false)
13    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
14    public class BaseTestTemplate {
15    
16    }

DemoActionTest,简单的测试用例,这里只是为了说明如何在这个框架里进行单元测试。所以我的目的达到了,简单吧。
01    package org.chinasb.framework.modules.demo.action;
02    
03    import java.util.Date;
04    
05    import javax.annotation.Resource;
06    
07    import org.chinasb.framework.core.base.test.BaseTestTemplate;
08    import org.chinasb.framework.modules.demo.model.Demo;
09    import org.chinasb.framework.modules.demo.service.DemoService;
10    import org.junit.After;
11    import org.junit.Before;
12    import org.junit.Test;
13    import org.springframework.test.context.transaction.AfterTransaction;
14    import org.springframework.test.context.transaction.BeforeTransaction;
15    
16    public class DemoActionTest extends BaseTestTemplate {
17    
18        @Resource
19        private DemoService demoService;
20    
21        @Before
22        public void setUp() throws Exception {
23        System.out.println("测试开始");
24        }
25    
26        @After
27        public void tearDown() throws Exception {
28        System.out.println("测试结束");
29        }
30    
31        @BeforeTransaction
32        public void beforeTransaction() {
33        System.out.println("事务开始");
34        }
35    
36        @AfterTransaction
37        public void afterTransaction() {
38        System.out.println("事务结束");
39        }
40    
41        @Test
42        public void testInsert() {
43        Demo demo = new Demo();
44        demo.setTitle("junit-test");
45        demo.setContent("junit-content");
46        demo.setPublishdate(new Date());
47        demoService.save(demo);
48        }
49    
50        @Test
51        public void testInsertMore() {
52        Demo[] demos = new Demo[10];
53        for (int i = 0; i < 10; i++) {
54            Demo demo = new Demo();
55            demo.setTitle("junit-test" + i);
56            demo.setContent("junit-content" + i);
57            demo.setPublishdate(new Date());
58            demos[i] = demo;
59        }
60        demoService.save(demos);
61        }
62    }

 

 

测试表:
01    /*
02    Navicat MySQL Data Transfer
03    
04    Source Server         : localhost
05    Source Server Version : 50150
06    Source Host           : localhost:3306
07    Source Database       : chinasb
08    
09    Target Server Type    : MYSQL
10    Target Server Version : 50150
11    File Encoding         : 65001
12    
13    Date: 2011-07-07 20:40:57
14    */
15    
16    SET FOREIGN_KEY_CHECKS=0;
17    -- ----------------------------
18    -- Table structure for `demo`
19    -- ----------------------------
20    DROP TABLE IF EXISTS `demo`;
21    CREATE TABLE `demo` (
22      `id` int(11) NOT NULL AUTO_INCREMENT,
23      `content` varchar(255) DEFAULT NULL,
24      `publishdate` datetime DEFAULT NULL,
25      `title` varchar(255) DEFAULT NULL,
26      PRIMARY KEY (`id`)
27    ) ENGINE=InnoDB AUTO_INCREMENT=133 DEFAULT CHARSET=utf8;
28    
29    -- ----------------------------
30    -- Records of demo
31    -- ----------------------------
32    INSERT INTO demo VALUES ('131', 'test', '2011-07-06 01:29:19', 'test');
33    INSERT INTO demo VALUES ('132', 'test-2', '2011-07-07 20:40:38', 'test-2');

众望所归,出图:

 

 

终于写完了,好累啊。下一步跟汪兄商量如何完美整合他那个强大的数据级权限中间件(ralasafe),这样在未来一投入使用即附带有权限控制,多爽。好了,大家看得也累,喜欢的,不喜欢的都出来拍拍砖吧。不对的地方,请各位N人多多指正。

 

×××:http://www.chinasb.org/wp-content/uploads/2011/07/framework.zip

Google Code:http://code.google.com/p/ssh-base-framework/

Google Code Download:http://code.google.com/p/ssh-base-framework/downloads/list

Google Code SVN:http://ssh-base-framework.googlecode.com/svn/trunk/