日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

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

 紫翰 2012-03-19
01 <?xml version="1.0" encoding="UTF-8"?>
02 <web-app xmlns:xsi="http://www./2001/XMLSchema-instance"
03     xmlns="http://java./xml/ns/javaee" xmlns:web="http://java./xml/ns/javaee/web-app_2_5.xsd"
04     xsi:schemaLocation="http://java./xml/ns/javaee http://java./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的參數(shù),這個參數(shù)就是設(shè)置struts2容器搜索action的包路徑。

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

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

我是用的struts.convention插件把所有action的父包都定義為我自定義的一個default包,大家也可以自定義其它父包,這樣定義的父包是所有action的默認(rèn)父包,當(dāng)然你也可以使用@package標(biāo)簽為action類定義不同的包。

下面介紹spring的配置文件:

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

首先前兩行配置是dwr和spring整合的配置第一個是配置dwr的遠(yuǎn)程代理對象的所在的包名,第二個則是dwr里的傳輸對象所在的包名。

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

現(xiàn)在來講講struts2的action用注解怎么實(shí)現(xiàn):

1.其實(shí)注解和xml配置步驟差不多首先肯定是配置包,但是我們前面用struts.convention配置了默認(rèn)包,所以也不用再配置,然后肯定是配置訪問的虛擬路勁咯,也就是配置namespace,使用@Namespace(value = "/mail")標(biāo)簽配置,value屬性是配置namespace的路徑。

2.配置好了namespace然后就是action咯,配置這個是使用@Action(value = "sendMail", results = { @Result(name = SUCCESS, type = "redirect", location = "../News.jsp") })標(biāo)簽,其中value是配置action的路徑,results是配置action的處理結(jié)果跳轉(zhuǎn)頁面,也可以配置多個頁面。

這樣就配置好了一個完整的action咯,我們現(xiàn)在要和spring整合就必須調(diào)用spring的bean,要調(diào)用bean很簡單定義一個私有變量,然后在變量上使用@resource標(biāo)簽就行了,但是需要注意的是這里的變量名必須和后面要講到的@service標(biāo)簽中的名字要一致才行,不然注入不進(jìn)來。

下面附上一個例子:

01 public class ActivityAction extends BaseAction {
02   
03     /**
04      
05      */
06     private static final long serialVersionUID = 5488332603981342055L;
07   
08     private long uid;
09   
10     private long eventId;
11   
12     private ActivityService activityService;
13   
14     /**
15      * 查詢活動列表
16      
17      * @return
18      * @throws Exception
19      */
20     @Action(value = "findActivityList")
21     public String findActivityList() throws Exception {
22         List<ActivityVo> activityVos = activityService.findActivityList();
23         String result = ListToJsonString(activityVos);
24         toWrite(result);
25         return null;
26     }
27   
28     /**
29      * 參加活動
30      
31      * @return
32      * @throws Exception
33      */
34     @Action(value = "joinActivity")
35     public String joinActivity() throws Exception {
36         boolean isSucc = activityService.insertActivityForUser(eventId, uid);
37         toWrite(isSucc + "");
38         return null;
39     }
40   
41     /**
42      * 根據(jù)用戶標(biāo)識查找活動列表
43      
44      * @return 我的活動列表
45      * @throws Exception
46      */
47     @Action(value = "findMyActivityList")
48     public String findMyActivityList() throws Exception {
49         List<ActivityVo> activityVos = activityService.findMyActivityList(uid);
50         String result = ListToJsonString(activityVos);
51         toWrite(result);
52         return null;
53     }
54   
55     @Resource
56     public void setActivityService(ActivityService activityService) {
57         this.activityService = activityService;
58     }
59   
60     public void setUid(long uid) {
61         this.uid = uid;
62     }
63   
64     public void setEventId(long eventId) {
65         this.eventId = eventId;
66     }
67   
68 }

然后來講講service的配置,配置方法是使用@service(value="serviceName")標(biāo)簽設(shè)置service,很簡單不用多講,而且調(diào)用dao的時候和action調(diào)用service一樣使用@resource標(biāo)簽引入屬性就行了,下面是例子源碼:

01 @Service(value = "activityService")
02 public class ActivityServiceImpl implements ActivityService {
03   
04     @Resource
05     ActivityDao activityDao;
06   
07     private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
08   
09     @Override
10     public boolean insertActivityForUser(long eventId, long uid) {
11         return activityDao.insertActivityForUser(eventId, uid);
12     }
13   
14     @Override
15     public List<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         return activityVos;
28     }
29   
30     @Override
31     public List<ActivityVo> findMyActivityList(long uid) {
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         return activityVos;
46     }
47 }

然后就是dao的配置和前面的差不多就是定義dao的時候是用@repository標(biāo)簽,直接貼代碼就行了:

01 @Repository(value = "activityDao")
02 public class ActivityDao 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     public boolean insertActivityForUser(long eventId, 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             return false;
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             return true;
28         }
29     }
30   
31     /**
32      * 查詢活動列表
33      
34      * @return 活動列表
35      */
36     @SuppressWarnings("unchecked")
37     public List<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         return list;
43     }
44   
45     /**
46      * 根據(jù)用戶標(biāo)識查詢用戶參加的所有活動
47      
48      * @param uid
49      *            用戶標(biāo)識
50      * @return 活動列表
51      */
52     @SuppressWarnings("unchecked")
53     public List<Activity> findMyActivityList(final long uid) {
54         return getHibernateTemplate().execute(new HibernateCallback() {
55   
56             @Override
57             public Object doInHibernate(Session session)
58                     throws HibernateException, 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                 return list;
64             }
65         });
66     }
67   
68 }

下面是BaseDao的代碼:

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

在這個類里面注入sessionFactory對象。

下面來講講dwr的配置,要配置dwr的遠(yuǎn)程代理對象在類上使用@RemoteProxy類中的方法@RemoteMethod這樣在javascript中直接用類名+方法名直接調(diào)用就行了。如果要調(diào)用spring的bean和上面一樣,就不不多說。如果dwr和jsp頁面?zhèn)鬏數(shù)臅r候需要用到j(luò)ava實(shí)體那么就在需要傳輸?shù)膶?shí)體類上用@DataTransferObject標(biāo)簽,才能正確轉(zhuǎn)換類型,不然會報(bào)異常。下面是例子:

01 @RemoteProxy
02 public class TestDwr implements Serializable {
03   
04     /**
05      
06      */
07     private static final long serialVersionUID = -2060851629180328131L;
08   
09     @RemoteMethod
10     public String testDwr() {
11         return "測試.";
12     }
13 }

實(shí)體的例子大家可以隨便定義一個類就行了加上標(biāo)簽就OK,這里就不列出來了。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多