struts2.2.1+spring 3.0.3+hibernate3.6+dwr3.0全注解整合详解

来源:互联网 发布:云计算安全论文 编辑:程序博客网 时间:2024/05/18 09:17

今天搭建了一个ssh+dwr框架,其实ssh框架配置和以前差不多,主要是使用了注解实现C和M层,下面就是web.xml配置

<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID"version="2.5">
    <display-name>nwr-web</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext*.xml</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>  
    <filter>
        <filter-name>struts-prepare</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.essential.action</param-value>
        </init-param>
    </filter>
    <filter>
        <filter-name>struts-execute</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
    </filter>
    <servlet>
        <servlet-name>dwr</servlet-name>
        <servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts-execute</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet-mapping>
        <servlet-name>dwr</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
74        <welcome-file>News.jsp</welcome-file>
75    </welcome-file-list>
76    <error-page>
77        <error-code>500</error-code>
78        <location>/error.jsp</location>
79    </error-page>
80    <error-page>
81        <error-code>402</error-code>
82        <location>/error.jsp</location>
83    </error-page>
84</web-app>

唯一需要说明一下的就是如果要使用struts2的注解就必须在配置filter的时候带上actionPackages的参数,这个参数就是设置struts2容器搜索action的包路径。

下面是struts.xml的配置文件:

01<?xmlversion="1.0"encoding="UTF-8"?>
02<!DOCTYPE struts PUBLIC
03    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
04    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
05<struts>
06    <packagename="default"extends="struts-default">
07        <global-results>
08            <resultname="error">error.jsp</result>
09            <resultname="input">error.jsp</result>
10        </global-results>
11    </package>
12    <constantname="struts.convention.default.parent.package"
13        value="default"/>
14</struts>

我是用的struts.convention插件把所有action的父包都定义为我自定义的一个default包,大家也可以自定义其它父包,这样定义的父包是所有action的默认父包,当然你也可以使用@package标签为action类定义不同的包。

下面介绍spring的配置文件:

01<?xmlversion="1.0"encoding="UTF-8"?>
02<beansxmlns="http://www.springframework.org/schema/beans"
03    xmlns:context="http://www.springframework.org/schema/context"
04    xmlns:dwr= "http://www.directwebremoting.org/schema/spring-dwr"
05    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"
06    xmlns:tx="http://www.springframework.org/schema/tx"
07    xsi:schemaLocation="
08       http://www.springframework.org/schema/beans
09       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10       http://www.springframework.org/schema/context
11       http://www.springframework.org/schema/context/spring-context-3.0.xsd
12       http://www.springframework.org/schema/tx
13       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
14       http://www.springframework.org/schema/aop
15       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
16       http://www.directwebremoting.org/schema/spring-dwr
17       http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd"
18       >
19    <dwr:annotation-scanscanRemoteProxy="true"base-package="com.essential.dwr"/>
20    <dwr:annotation-scanscanDataTransferObject="true"base-package="com.essential.entity"/>
21    <context:component-scanbase-package="com.essential"/>
22     
23    <beanid="configurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
24        <propertyname="locations">
25           <value>classpath*:init.properties</value>
26        </property>
27    </bean>
28     
29    <beanid="mainDataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close">
30       <propertyname="driverClass"value="${jdbc.driverClass}"></property>
31       <propertyname="jdbcUrl"value="${jdbc.jdbcUrl}"></property>
32       <propertyname="user"value="${jdbc.user}"></property>
33       <propertyname="password"value="${jdbc.password}"></property>
34   
35       <propertyname="maxPoolSize"value="${jdbc.maxPoolSize}"></property>
36       <propertyname="minPoolSize"value="${jdbc.minPoolSize}"></property>
37       <propertyname="initialPoolSize"value="${jdbc.initialPoolSize}"></property>
38       <propertyname="idleConnectionTestPeriod"value="${jdbc.idleConnectionTestPeriod}"></property>
39       <propertyname="maxIdleTime"value="${jdbc.maxIdleTime}"></property>
40       <propertyname="acquireIncrement"value="${jdbc.acquireIncrement}"/>   
41    </bean>
42 
43    <beanid="dataSource"
44        class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
45        <propertyname="targetDataSource">
46            <reflocal="mainDataSource"/>
47        </property>
48    </bean>
49 
50    <beanid="sessionFactory"
51        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
52        <propertyname="dataSource">
53            <refbean="dataSource"/>
54        </property>
55 
56        <propertyname="hibernateProperties">
57            <props>
58                <propkey="hibernate.dialect">${hibernate.dialect}</prop>
59                <propkey="hibernate.show_sql">${hibernate.show_sql}</prop>
60                <propkey="hibernate.format_sql">${hibernate.format_sql}</prop>
61                <propkey="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
62                <propkey="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
63            </props>
64        </property>
65 
66        <propertyname="packagesToScan"value="${hibernate.packagesToScan}"/>
67    </bean>
68 
69    <beanid="transactionManager"
70        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
71        <propertyname="sessionFactory">
72            <reflocal="sessionFactory"/>
73        </property>
74    </bean>
75 
76    <tx:adviceid="txAdvice"transaction-manager="transactionManager">
77        <tx:attributes>
78            <tx:methodname="upd*"propagation="REQUIRED"read-only="false"/>
79            <tx:methodname="del*"propagation="REQUIRED"read-only="false"/>
80            <tx:methodname="add*"propagation="REQUIRED"read-only="false"/>
81            <tx:methodname="insert*"propagation="REQUIRED"read-only="false"/>
82            <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
83            <tx:methodname="query*"propagation="SUPPORTS"read-only="true"/>
84            <tx:methodname="*"propagation="SUPPORTS"read-only="true"/>
85        </tx:attributes>
86    </tx:advice>
87 
88    <aop:config>
89        <aop:pointcutid="productServiceMethods"
90            expression="${spring.execution}"/>
91        <aop:advisoradvice-ref="txAdvice"pointcut-ref="productServiceMethods"/>
92    </aop:config>
93     
94</beans>

首先前两行配置是dwr和spring整合的配置第一个是配置dwr的远程代理对象的所在的包名,第二个则是dwr里的传输对象所在的包名。

下面一行是spring搜索bean的包名。下面其他的配置和以前没什么变化。

现在来讲讲struts2的action用注解怎么实现:

1.其实注解和xml配置步骤差不多首先肯定是配置包,但是我们前面用struts.convention配置了默认包,所以也不用再配置,然后肯定是配置访问的虚拟路劲咯,也就是配置namespace,使用@Namespace(value = "/mail")标签配置,value属性是配置namespace的路径。

2.配置好了namespace然后就是action咯,配置这个是使用@Action(value = "sendMail", results = { @Result(name = SUCCESS, type = "redirect", location = "../News.jsp") })标签,其中value是配置action的路径,results是配置action的处理结果跳转页面,也可以配置多个页面。

这样就配置好了一个完整的action咯,我们现在要和spring整合就必须调用spring的bean,要调用bean很简单定义一个私有变量,然后在变量上使用@resource标签就行了,但是需要注意的是这里的变量名必须和后面要讲到的@service标签中的名字要一致才行,不然注入不进来。

下面附上一个例子:

01public classActivityAction extends BaseAction {
02 
03    /**
04     *
05     */
06    privatestatic final long serialVersionUID = 5488332603981342055L;
07 
08    privatelong uid;
09 
10    privatelong eventId;
11 
12    privateActivityService activityService;
13 
14    /**
15     * 查询活动列表
16     *
17     * @return
18     * @throws Exception
19     */
20    @Action(value ="findActivityList")
21    publicString findActivityList() throwsException {
22        List<ActivityVo> activityVos = activityService.findActivityList();
23        String result = ListToJsonString(activityVos);
24        toWrite(result);
25        returnnull;
26    }
27 
28    /**
29     * 参加活动
30     *
31     * @return
32     * @throws Exception
33     */
34    @Action(value ="joinActivity")
35    publicString joinActivity() throwsException {
36        booleanisSucc = activityService.insertActivityForUser(eventId, uid);
37        toWrite(isSucc +"");
38        returnnull;
39    }
40 
41    /**
42     * 根据用户标识查找活动列表
43     *
44     * @return 我的活动列表
45     * @throws Exception
46     */
47    @Action(value ="findMyActivityList")
48    publicString findMyActivityList() throwsException {
49        List<ActivityVo> activityVos = activityService.findMyActivityList(uid);
50        String result = ListToJsonString(activityVos);
51        toWrite(result);
52        returnnull;
53    }
54 
55    @Resource
56    publicvoid setActivityService(ActivityService activityService) {
57        this.activityService = activityService;
58    }
59 
60    publicvoid setUid(longuid) {
61        this.uid = uid;
62    }
63 
64    publicvoid setEventId(longeventId) {
65        this.eventId = eventId;
66    }
67 
68}

然后来讲讲service的配置,配置方法是使用@service(value="serviceName")标签设置service,很简单不用多讲,而且调用dao的时候和action调用service一样使用@resource标签引入属性就行了,下面是例子源码:

01@Service(value ="activityService")
02public classActivityServiceImpl implementsActivityService {
03 
04    @Resource
05    ActivityDao activityDao;
06 
07    privateDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
08 
09    @Override
10    publicboolean insertActivityForUser(longeventId, long uid) {
11        returnactivityDao.insertActivityForUser(eventId, uid);
12    }
13 
14    @Override
15    publicList<ActivityVo> findActivityList() {
16        List<Activity> list = activityDao.findActivityList();
17        List<ActivityVo> activityVos =new ArrayList<ActivityVo>();
18        for(Activity activity : list) {
19            ActivityVo activityVo =new ActivityVo();
20            activityVo.setId(activity.getId());
21            activityVo.setTitle(activity.getTitle());
22            activityVo.setPublishTime(df.format(activity.getPublishTime()));
23            activityVo.setImagurl(activity.getImagurl());
24            activityVo.setContent(activity.getContent());
25            activityVos.add(activityVo);
26        }
27        returnactivityVos;
28    }
29 
30    @Override
31    publicList<ActivityVo> findMyActivityList(longuid) {
32        List<Activity> list = activityDao.findMyActivityList(uid);
33        List<ActivityVo> activityVos =new ArrayList<ActivityVo>();
34        for(Activity activity : list) {
35            ActivityVo activityVo =new ActivityVo();
36            activityVo.setId(activity.getId());
37            activityVo.setTitle(activity.getTitle());
38            activityVo.setPublishTime(df.format(activity.getPublishTime()));
39            activityVo.setImagurl(activity.getImagurl());
40            activityVo.setDatetime(activity.getDatetime());
41            activityVo.setDescription(activity.getDescription());
42            activityVo.setContent(activity.getContent());
43            activityVos.add(activityVo);
44        }
45        returnactivityVos;
46    }
47}

然后就是dao的配置和前面的差不多就是定义dao的时候是用@repository标签,直接贴代码就行了:

01@Repository(value ="activityDao")
02public classActivityDao extends BaseDao<Activity> {
03 
04    /**
05     * 参加活动
06     *
07     * @param eventId
08     *            活动ID
09     * @param uid
10     *            用户ID
11     * @return 成功返回true,失败返回false
12     */
13    @SuppressWarnings("unchecked")
14    publicboolean insertActivityForUser(longeventId, long uid) {
15        Session session = getSession();
16        Query query = session
17                .createSQLQuery("select au.aid from activity_users au where au.aid=:aid and au.uid=:uid");
18        List list = query.setParameter("uid", uid).setParameter("aid", eventId)
19                .list();
20        if(list.size() > 0) {
21            returnfalse;
22        } else {
23            session.createSQLQuery(
24                    "insert into activity_users(aid,uid) values(:aid,:uid)")
25                    .setParameter("uid", uid).setParameter("aid", eventId)
26                    .executeUpdate();
27            returntrue;
28        }
29    }
30 
31    /**
32     * 查询活动列表
33     *
34     * @return 活动列表
35     */
36    @SuppressWarnings("unchecked")
37    publicList<Activity> findActivityList() {
38        Session session = getSession();
39        List<Activity> list = session.createQuery(
40                "from Activity where status = 2 order by publishTime desc")
41                .setMaxResults(10).list();
42        returnlist;
43    }
44 
45    /**
46     * 根据用户标识查询用户参加的所有活动
47     *
48     * @param uid
49     *            用户标识
50     * @return 活动列表
51     */
52    @SuppressWarnings("unchecked")
53    publicList<Activity> findMyActivityList(finallong uid) {
54        returngetHibernateTemplate().execute(newHibernateCallback() {
55 
56            @Override
57            publicObject doInHibernate(Session session)
58                    throwsHibernateException, SQLException {
59                List<Activity> list = session
60                        .createQuery(
61                                "select a from Activity a left join a.users u where u.id=:uid order by a.publishTime desc")
62                        .setParameter("uid", uid).list();
63                returnlist;
64            }
65        });
66    }
67 
68}

下面是BaseDao的代码:

01public classBaseDao<E> extends HibernateDaoSupport {
02 
03    @Resource(name ="sessionFactory")
04    publicvoid setInjectionSessionFacotry(SessionFactory sessionFacotry) {
05        super.setSessionFactory(sessionFacotry);
06    }
07 
08    @PostConstruct
09    publicvoid injectSessionFactory() {
10        logger.info(super.getSessionFactory());
11    }
12 
13    publicSerializable save(E entity) {
14        returngetHibernateTemplate().save(entity);
15    }
16 
17    publicvoid update(E entity) {
18        getHibernateTemplate().update(entity);
19    }
20 
21    publicvoid delete(E entity) {
22        getHibernateTemplate().delete(entity);
23    }
24 
25    publicUser query(long id) {
26        returngetHibernateTemplate().get(User.class, id);
27    }
28 
29}

在这个类里面注入sessionFactory对象。

下面来讲讲dwr的配置,要配置dwr的远程代理对象在类上使用@RemoteProxy类中的方法@RemoteMethod这样在javascript中直接用类名+方法名直接调用就行了。如果要调用spring的bean和上面一样,就不不多说。如果dwr和jsp页面传输的时候需要用到java实体那么就在需要传输的实体类上用@DataTransferObject标签,才能正确转换类型,不然会报异常。下面是例子:

01@RemoteProxy
02public classTestDwr implements Serializable {
03 
04    /**
05     *
06     */
07    privatestatic final long serialVersionUID = -2060851629180328131L;
08 
09    @RemoteMethod
10    publicString testDwr() {
11        return"测试.";
12    }
13}

实体的例子大家可以随便定义一个类就行了加上标签就OK,这里就不列出来了。

下面是jsp使用dwr必须引入3个jsp:

1<scripttype="text/javascript"src="<%=path %>/dwr/engine.js"></script>
2<scripttype="text/javascript"src="<%=path %>/dwr/util.js"></script>
1<scripttype="text/javascript"src="<%=path %>/dwr/interface/TestDwr .js"></script>

前面2个是dwr必须要使用的2个js包,后面一个就是你在java中定义的类.这样就可以调用里面的方法了。

今天搭建了一个ssh+dwr框架,其实ssh框架配置和以前差不多,主要是使用了注解实现C和M层,下面就是web.xml配置

01<?xml version="1.0"encoding="UTF-8"?>
02<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03    xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
04    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
05    id="WebApp_ID"version="2.5">
06    <display-name>nwr-web</display-name>
07    <context-param>
08        <param-name>contextConfigLocation</param-name>
09        <param-value>classpath*:applicationContext*.xml</param-value>
10    </context-param>
11    <context-param>
12        <param-name>log4jConfigLocation</param-name>
13        <param-value>/WEB-INF/classes/log4j.properties</param-value>
14    </context-param>
15    <context-param>
16        <param-name>log4jRefreshInterval</param-name>
17        <param-value>60000</param-value>
18    </context-param>
19    <listener>
20        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
21    </listener>
22    <listener>
23        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
24    </listener>  
25    <filter>
26        <filter-name>struts-prepare</filter-name>
27        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
28        <init-param>
29            <param-name>actionPackages</param-name>
30            <param-value>com.essential.action</param-value>
31        </init-param>
32    </filter>
33    <filter>
34        <filter-name>struts-execute</filter-name>
35        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
36    </filter>
37    <servlet>
38        <servlet-name>dwr</servlet-name>
39        <servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class>
40        <init-param>
41            <param-name>debug</param-name>
42            <param-value>true</param-value>
43        </init-param>
44    </servlet>
45    <filter-mapping>
46        <filter-name>struts-prepare</filter-name>
47        <url-pattern>/*</url-pattern>
48    </filter-mapping>
49    <filter-mapping>
50        <filter-name>struts-execute</filter-name>
51        <url-pattern>/*</url-pattern>
52    </filter-mapping>
53    <filter>
54        <filter-name>characterEncodingFilter</filter-name>
55        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
56        <init-param>
57            <param-name>encoding</param-name>
58            <param-value>UTF-8</param-value>
59        </init-param>
60        <init-param>
61            <param-name>forceEncoding</param-name>
62            <param-value>true</param-value>
63        </init-param>
64    </filter>
65    <filter-mapping>
66        <filter-name>characterEncodingFilter</filter-name>
67        <url-pattern>/*</url-pattern>
68    </filter-mapping>
69    <servlet-mapping>
70        <servlet-name>dwr</servlet-name>
71        <url-pattern>/dwr/*</url-pattern>
72    </servlet-mapping>
73    <welcome-file-list>
74        <welcome-file>News.jsp</welcome-file>
75    </welcome-file-list>
76    <error-page>
77        <error-code>500</error-code>
78        <location>/error.jsp</location>
79    </error-page>
80    <error-page>
81        <error-code>402</error-code>
82        <location>/error.jsp</location>
83    </error-page>
84</web-app>

唯一需要说明一下的就是如果要使用struts2的注解就必须在配置filter的时候带上actionPackages的参数,这个参数就是设置struts2容器搜索action的包路径。

下面是struts.xml的配置文件:

01<?xmlversion="1.0"encoding="UTF-8"?>
02<!DOCTYPE struts PUBLIC
03    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
04    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
05<struts>
06    <packagename="default"extends="struts-default">
07        <global-results>
08            <resultname="error">error.jsp</result>
09            <resultname="input">error.jsp</result>
10        </global-results>
11    </package>
12    <constantname="struts.convention.default.parent.package"
13        value="default"/>
14</struts>

我是用的struts.convention插件把所有action的父包都定义为我自定义的一个default包,大家也可以自定义其它父包,这样定义的父包是所有action的默认父包,当然你也可以使用@package标签为action类定义不同的包。

下面介绍spring的配置文件:

01<?xmlversion="1.0"encoding="UTF-8"?>
02<beansxmlns="http://www.springframework.org/schema/beans"
03    xmlns:context="http://www.springframework.org/schema/context"
04    xmlns:dwr= "http://www.directwebremoting.org/schema/spring-dwr"
05    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"
06    xmlns:tx="http://www.springframework.org/schema/tx"
07    xsi:schemaLocation="
08       http://www.springframework.org/schema/beans
09       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10       http://www.springframework.org/schema/context
11       http://www.springframework.org/schema/context/spring-context-3.0.xsd
12       http://www.springframework.org/schema/tx
13       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
14       http://www.springframework.org/schema/aop
15       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
16       http://www.directwebremoting.org/schema/spring-dwr
17       http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd"
18       >
19    <dwr:annotation-scanscanRemoteProxy="true"base-package="com.essential.dwr"/>
20    <dwr:annotation-scanscanDataTransferObject="true"base-package="com.essential.entity"/>
21    <context:component-scanbase-package="com.essential"/>
22     
23    <beanid="configurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
24        <propertyname="locations">
25           <value>classpath*:init.properties</value>
26        </property>
27    </bean>
28     
29    <beanid="mainDataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close">
30       <propertyname="driverClass"value="${jdbc.driverClass}"></property>
31       <propertyname="jdbcUrl"value="${jdbc.jdbcUrl}"></property>
32       <propertyname="user"value="${jdbc.user}"></property>
33       <propertyname="password"value="${jdbc.password}"></property>
34   
35       <propertyname="maxPoolSize"value="${jdbc.maxPoolSize}"></property>
36       <propertyname="minPoolSize"value="${jdbc.minPoolSize}"></property>
37       <propertyname="initialPoolSize"value="${jdbc.initialPoolSize}"></property>
38       <propertyname="idleConnectionTestPeriod"value="${jdbc.idleConnectionTestPeriod}"></property>
39       <propertyname="maxIdleTime"value="${jdbc.maxIdleTime}"></property>
40       <propertyname="acquireIncrement"value="${jdbc.acquireIncrement}"/>   
41    </bean>
42 
43    <beanid="dataSource"
44        class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
45        <propertyname="targetDataSource">
46            <reflocal="mainDataSource"/>
47        </property>
48    </bean>
49 
50    <beanid="sessionFactory"
51        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
52        <propertyname="dataSource">
53            <refbean="dataSource"/>
54        </property>
55 
56        <propertyname="hibernateProperties">
57            <props>
58                <propkey="hibernate.dialect">${hibernate.dialect}</prop>
59                <propkey="hibernate.show_sql">${hibernate.show_sql}</prop>
60                <propkey="hibernate.format_sql">${hibernate.format_sql}</prop>
61                <propkey="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
62                <propkey="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
63            </props>
64        </property>
65 
66        <propertyname="packagesToScan"value="${hibernate.packagesToScan}"/>
67    </bean>
68 
69    <beanid="transactionManager"
70        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
71        <propertyname="sessionFactory">
72            <reflocal="sessionFactory"/>
73        </property>
74    </bean>
75 
76    <tx:adviceid="txAdvice"transaction-manager="transactionManager">
77        <tx:attributes>
78            <tx:methodname="upd*"propagation="REQUIRED"read-only="false"/>
79            <tx:methodname="del*"propagation="REQUIRED"read-only="false"/>
80            <tx:methodname="add*"propagation="REQUIRED"read-only="false"/>
81            <tx:methodname="insert*"propagation="REQUIRED"read-only="false"/>
82            <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
83            <tx:methodname="query*"propagation="SUPPORTS"read-only="true"/>
84            <tx:methodname="*"propagation="SUPPORTS"read-only="true"/>
85        </tx:attributes>
86    </tx:advice>
87 
88    <aop:config>
89        <aop:pointcutid="productServiceMethods"
90            expression="${spring.execution}"/>
91        <aop:advisoradvice-ref="txAdvice"pointcut-ref="productServiceMethods"/>
92    </aop:config>
93     
94</beans>

首先前两行配置是dwr和spring整合的配置第一个是配置dwr的远程代理对象的所在的包名,第二个则是dwr里的传输对象所在的包名。

下面一行是spring搜索bean的包名。下面其他的配置和以前没什么变化。

现在来讲讲struts2的action用注解怎么实现:

1.其实注解和xml配置步骤差不多首先肯定是配置包,但是我们前面用struts.convention配置了默认包,所以也不用再配置,然后肯定是配置访问的虚拟路劲咯,也就是配置namespace,使用@Namespace(value = "/mail")标签配置,value属性是配置namespace的路径。

2.配置好了namespace然后就是action咯,配置这个是使用@Action(value = "sendMail", results = { @Result(name = SUCCESS, type = "redirect", location = "../News.jsp") })标签,其中value是配置action的路径,results是配置action的处理结果跳转页面,也可以配置多个页面。

这样就配置好了一个完整的action咯,我们现在要和spring整合就必须调用spring的bean,要调用bean很简单定义一个私有变量,然后在变量上使用@resource标签就行了,但是需要注意的是这里的变量名必须和后面要讲到的@service标签中的名字要一致才行,不然注入不进来。

下面附上一个例子:

01public classActivityAction extends BaseAction {
02 
03    /**
04     *
05     */
06    privatestatic final long serialVersionUID = 5488332603981342055L;
07 
08    privatelong uid;
09 
10    privatelong eventId;
11 
12    privateActivityService activityService;
13 
14    /**
15     * 查询活动列表
16     *
17     * @return
18     * @throws Exception
19     */
20    @Action(value ="findActivityList")
21    publicString findActivityList() throwsException {
22        List<ActivityVo> activityVos = activityService.findActivityList();
23        String result = ListToJsonString(activityVos);
24        toWrite(result);
25        returnnull;
26    }
27 
28    /**
29     * 参加活动
30     *
31     * @return
32     * @throws Exception
33     */
34    @Action(value ="joinActivity")
35    publicString joinActivity() throwsException {
36        booleanisSucc = activityService.insertActivityForUser(eventId, uid);
37        toWrite(isSucc +"");
38        returnnull;
39    }
40 
41    /**
42     * 根据用户标识查找活动列表
43     *
44     * @return 我的活动列表
45     * @throws Exception
46     */
47    @Action(value ="findMyActivityList")
48    publicString findMyActivityList() throwsException {
49        List<ActivityVo> activityVos = activityService.findMyActivityList(uid);
50        String result = ListToJsonString(activityVos);
51        toWrite(result);
52        returnnull;
53    }
54 
55    @Resource
56    publicvoid setActivityService(ActivityService activityService) {
57        this.activityService = activityService;
58    }
59 
60    publicvoid setUid(longuid) {
61        this.uid = uid;
62    }
63 
64    publicvoid setEventId(longeventId) {
65        this.eventId = eventId;
66    }
67 
68}

然后来讲讲service的配置,配置方法是使用@service(value="serviceName")标签设置service,很简单不用多讲,而且调用dao的时候和action调用service一样使用@resource标签引入属性就行了,下面是例子源码:

01@Service(value ="activityService")
02public classActivityServiceImpl implementsActivityService {
03 
04    @Resource
05    ActivityDao activityDao;
06 
07    privateDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
08 
09    @Override
10    publicboolean insertActivityForUser(longeventId, long uid) {
11        returnactivityDao.insertActivityForUser(eventId, uid);
12    }
13 
14    @Override
15    publicList<ActivityVo> findActivityList() {
16        List<Activity> list = activityDao.findActivityList();
17        List<ActivityVo> activityVos =new ArrayList<ActivityVo>();
18        for(Activity activity : list) {
19            ActivityVo activityVo =new ActivityVo();
20            activityVo.setId(activity.getId());
21            activityVo.setTitle(activity.getTitle());
22            activityVo.setPublishTime(df.format(activity.getPublishTime()));
23            activityVo.setImagurl(activity.getImagurl());
24            activityVo.setContent(activity.getContent());
25            activityVos.add(activityVo);
26        }
27        returnactivityVos;
28    }
29 
30    @Override
31    publicList<ActivityVo> findMyActivityList(longuid) {
32        List<Activity> list = activityDao.findMyActivityList(uid);
33        List<ActivityVo> activityVos =new ArrayList<ActivityVo>();
34        for(Activity activity : list) {
35            ActivityVo activityVo =new ActivityVo();
36            activityVo.setId(activity.getId());
37            activityVo.setTitle(activity.getTitle());
38            activityVo.setPublishTime(df.format(activity.getPublishTime()));
39            activityVo.setImagurl(activity.getImagurl());
40            activityVo.setDatetime(activity.getDatetime());
41            activityVo.setDescription(activity.getDescription());
42            activityVo.setContent(activity.getContent());
43            activityVos.add(activityVo);
44        }
45        returnactivityVos;
46    }
47}

然后就是dao的配置和前面的差不多就是定义dao的时候是用@repository标签,直接贴代码就行了:

01@Repository(value ="activityDao")
02public classActivityDao extends BaseDao<Activity> {
03 
04    /**
05     * 参加活动
06     *
07     * @param eventId
08     *            活动ID
09     * @param uid
10     *            用户ID
11     * @return 成功返回true,失败返回false
12     */
13    @SuppressWarnings("unchecked")
14    publicboolean insertActivityForUser(longeventId, long uid) {
15        Session session = getSession();
16        Query query = session
17                .createSQLQuery("select au.aid from activity_users au where au.aid=:aid and au.uid=:uid");
18        List list = query.setParameter("uid", uid).setParameter("aid", eventId)
19                .list();
20        if(list.size() > 0) {
21            returnfalse;
22        } else {
23            session.createSQLQuery(
24                    "insert into activity_users(aid,uid) values(:aid,:uid)")
25                    .setParameter("uid", uid).setParameter("aid", eventId)
26                    .executeUpdate();
27            returntrue;
28        }
29    }
30 
31    /**
32     * 查询活动列表
33     *
34     * @return 活动列表
35     */
36    @SuppressWarnings("unchecked")
37    publicList<Activity> findActivityList() {
38        Session session = getSession();
39        List<Activity> list = session.createQuery(
40                "from Activity where status = 2 order by publishTime desc")
41                .setMaxResults(10).list();
42        returnlist;
43    }
44 
45    /**
46     * 根据用户标识查询用户参加的所有活动
47     *
48     * @param uid
49     *            用户标识
50     * @return 活动列表
51     */
52    @SuppressWarnings("unchecked")
53    publicList<Activity> findMyActivityList(finallong uid) {
54        returngetHibernateTemplate().execute(newHibernateCallback() {
55 
56            @Override
57            publicObject doInHibernate(Session session)
58                    throwsHibernateException, SQLException {
59                List<Activity> list = session
60                        .createQuery(
61                                "select a from Activity a left join a.users u where u.id=:uid order by a.publishTime desc")
62                        .setParameter("uid", uid).list();
63                returnlist;
64            }
65        });
66    }
67 
68}

下面是BaseDao的代码:

01public classBaseDao<E> extends HibernateDaoSupport {
02 
03    @Resource(name ="sessionFactory")
04    publicvoid setInjectionSessionFacotry(SessionFactory sessionFacotry) {
05        super.setSessionFactory(sessionFacotry);
06    }
07 
08    @PostConstruct
09    publicvoid injectSessionFactory() {
10        logger.info(super.getSessionFactory());
11    }
12 
13    publicSerializable save(E entity) {
14        returngetHibernateTemplate().save(entity);
15    }
16 
17    publicvoid update(E entity) {
18        getHibernateTemplate().update(entity);
19    }
20 
21    publicvoid delete(E entity) {
22        getHibernateTemplate().delete(entity);
23    }
24 
25    publicUser query(long id) {
26        returngetHibernateTemplate().get(User.class, id);
27    }
28 
29}

在这个类里面注入sessionFactory对象。

下面来讲讲dwr的配置,要配置dwr的远程代理对象在类上使用@RemoteProxy类中的方法@RemoteMethod这样在javascript中直接用类名+方法名直接调用就行了。如果要调用spring的bean和上面一样,就不不多说。如果dwr和jsp页面传输的时候需要用到java实体那么就在需要传输的实体类上用@DataTransferObject标签,才能正确转换类型,不然会报异常。下面是例子:

01@RemoteProxy
02public classTestDwr implements Serializable {
03 
04    /**
05     *
06     */
07    privatestatic final long serialVersionUID = -2060851629180328131L;
08 
09    @RemoteMethod
10    publicString testDwr() {
11        return"测试.";
12    }
13}

实体的例子大家可以随便定义一个类就行了加上标签就OK,这里就不列出来了。

下面是jsp使用dwr必须引入3个jsp:

1<scripttype="text/javascript"src="<%=path %>/dwr/engine.js"></script>
2<scripttype="text/javascript"src="<%=path %>/dwr/util.js"></script>
1<scripttype="text/javascript"src="<%=path %>/dwr/interface/TestDwr .js"></script>

前面2个是dwr必须要使用的2个js包,后面一个就是你在java中定义的类.这样就可以调用里面的方法了。


 转自:http://blog.csdn.net/yaoyeyzq/article/details/6623571


原创粉丝点击