struts-2.3.16.3+hibernate-3.2.5+spring-2.5全註解配置

一、新建項目  結構以下:html

 

二、導入相關的jarjava

三、整合步驟先整合 Spring2.5+Hibernate3.3 成功後在整合 Struts2 這樣就不容易報錯,並且 報錯誤後也便於找出問題。
applicationContext.xml
spring配置文件模版能夠到 spring自帶的一些例子中進行拷貝。web

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:jee="http://www.springframework.org/schema/jee"
 6     xsi:schemaLocation="
 7             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
 8             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
 9             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
10             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
11             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
12 
13     <!-- 加載數據庫屬性配置文件 -->
14     <context:property-placeholder location="classpath:db.properties" />
15     <!-- 掃描包的範圍 -->
16     <context:component-scan base-package="demo.loading.*" />
17 
18     <!-- 數據庫鏈接池c3p0配置 -->
19     <!-- destroy-method="close"的做用是當數據庫鏈接不使用的時候,就把該鏈接從新放到數據池中,方便下次使用調用 -->
20     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
21         destroy-method="close">
22         <property name="driverClass" value="${driverClassName}"></property>
23         <property name="jdbcUrl" value="${url}"></property>
24         <property name="user" value="${username}"></property>
25         <property name="password" value="${password}"></property>
26 
27         <!-- 鏈接池中的最大鏈接數 -->
28         <property name="maxPoolSize" value="${maxPoolSize}" />
29 
30         <!-- 鏈接池中的最小鏈接數 -->
31         <property name="minPoolSize" value="${minPoolSize}" />
32 
33         <!-- 初始化鏈接池中的 鏈接數,取值 在 minPoolSize 和 maxPoolSize 之間,default:3 -->
34         <property name="initialPoolSize" value="${initialPoolSize}" />
35 
36         <!-- 最大空閒時間,60s內該鏈接沒有被使用則被丟棄,若爲0 永不丟棄.default:0 -->
37         <property name="maxIdleTime" value="${maxIdleTime}" />
38 
39         <!-- 當鏈接數不夠時,每次同時建立多少個鏈接 -->
40         <property name="acquireIncrement" value="${acquireIncrement}" />
41 
42         <!-- 每60s檢查鏈接池中的全部空間鏈接,若是沒有被使用,就被放棄, default:0 -->
43         <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}" />
44     </bean>
45 
46     <!-- 將Hibernate中的事物交給Spring進行接管 -->
47     <bean id="sessionFactory"
48         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
49         <!-- 指定sessiongFactory中的數據源 -->
50         <property name="dataSource" ref="dataSource"></property>
51         <!-- 指定hibernate的屬性 -->
52         <property name="hibernateProperties">
53             <props>
54                 <!-- hibernate使用的 方言 -->
55                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
56                 <!-- 根據實體的映射文件生成表結構 -->
57                 <prop key="hibernate.hbm2ddl.auto">update</prop>
58                 <!-- 是否打印出sql語句 -->
59                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
60                 <!-- 格式化sql -->
61                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
62             </props>
63         </property>
64         <!-- 配置自動掃描實體類 -->
65         <property name="packagesToScan">
66             <list>
67                 <value>demo.loading.*</value>
68             </list>
69         </property>
70     </bean>
71 
72     <!-- 配置使用基於Hibernate的事務管理器 -->
73     <bean id="txManager"
74         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
75         <!-- spring須要經過sessionFactory來開啓事務 -->
76         <property name="sessionFactory" ref="sessionFactory"></property>
77     </bean>
78 
79     <!--Spring中的事物配置聲明.1 基於xml 配置方式 2.基於註解來聲明那些類 -->
80     <tx:annotation-driven proxy-target-class="true" transaction-manager="txManager" />
81 </beans>

 

db.properties 數據庫相關配置的信息spring

 

demo.loading.entity 新建實體Usersql

 1 package demo.loading.entity;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.GenerationType;
 9 import javax.persistence.Id;
10 import javax.persistence.Table;
11 import javax.persistence.Temporal;
12 import javax.persistence.TemporalType;
13 
14 @Entity        //註釋指名這是一個實體Bean
15 @Table(name = "user")        //爲實體Bean指定對應數據庫表
16 public class User {
17     private Integer id;
18     private String username;
19     private String password;
20     private String address;
21     private String phoneNumber;
22     private Date createTime;
23     private Date updateTime;
24 
25     @Id        //註解聲明瞭該實體Bean的標識屬性
26     @GeneratedValue(strategy = GenerationType.AUTO)        //註解能夠定義該標識符的生成策略。自動增加
27     @Column(name = "ID", length = 20)        //
28     public Integer getId() {
29         return id;
30     }
31 
32     public void setId(Integer id) {
33         this.id = id;
34     }
35 
36     public String getUsername() {
37         return username;
38     }
39 
40     public void setUsername(String username) {
41         this.username = username;
42     }
43 
44     public String getPassword() {
45         return password;
46     }
47 
48     public void setPassword(String password) {
49         this.password = password;
50     }
51 
52     public String getAddress() {
53         return address;
54     }
55 
56     public void setAddress(String address) {
57         this.address = address;
58     }
59 
60     public String getPhoneNumber() {
61         return phoneNumber;
62     }
63 
64     public void setPhoneNumber(String phoneNumber) {
65         this.phoneNumber = phoneNumber;
66     }
67 
68     @Temporal(TemporalType.TIMESTAMP)
69     public Date getCreateTime() {
70         return createTime;
71     }
72 
73     public void setCreateTime(Date createTime) {
74         this.createTime = createTime;
75     }
76 
77     @Temporal(TemporalType.TIMESTAMP)
78     public Date getUpdateTime() {
79         return updateTime;
80     }
81 
82     public void setUpdateTime(Date updateTime) {
83         this.updateTime = updateTime;
84     }
85 
86 }

demo.loading.common.db   新建公用的接口IBaseDao數據庫

  1 package demo.loading.common.db;
  2 
  3 import java.io.Serializable;
  4 import java.util.List;
  5 
  6 /**
  7  * DAO 基類接口
  8  * @param <T> T pojo類型
  9  * @param <ID> ID類型
 10  */
 11 public interface IBaseDao<T, ID extends Serializable> {
 12     /**
 13      * 得到持久化對象的類型
 14      * @return
 15      */
 16     public abstract Class<T> getPersistentClass();
 17 
 18     /**
 19      * 保存
 20      * @param entity 實體類
 21      */
 22     public abstract void save(T entity);
 23 
 24     /**
 25      * 刪除
 26      * @param entity 實體類
 27      */
 28     public abstract void delete(T entity);
 29 
 30     /**
 31      * 與findByProperty類似,當properyName == value 時把相應的記錄刪除
 32      */
 33     public abstract void deleteByProperty(String propertyName, Object value);
 34 
 35     /**
 36      * 更新
 37      * @param entity
 38      */
 39     public abstract void update(T entity);
 40 
 41     /**
 42      * 保存或者更新
 43      * @param entity
 44      */
 45     public abstract void saveOrUpdate(T entity);
 46 
 47     /**
 48      * 查詢全部
 49      */
 50     public abstract List<T> findAll();
 51 
 52     /**
 53      * 查找全部,並分頁
 54      * @param page 要返回的頁數
 55      * @param pageSize 沒有記錄數
 56      * @return
 57      */
 58     public abstract List<T> findAll(int page, int pageSize);
 59 
 60     /**
 61      * 根據id查找
 62      * @param id
 63      * @return
 64      */
 65     public abstract T findById(ID id);
 66 
 67     public abstract List<T> findByExample(T entity);
 68 
 69     /**
 70      * 經過屬性查找
 71      * @param propertyName 屬性名稱
 72      * @param value 屬性的值
 73      * @return
 74      */
 75     public abstract List<T> findByProperty(String propertyName, Object value);
 76 
 77     /**
 78      * 經過多個屬性查找
 79      * @param propertyNames 屬性名稱數組
 80      * @param values  屬性值數組
 81      * @return
 82      */
 83     public abstract List<T> findByPropertys(String[] propertyNames, Object[] values);
 84 
 85     /**
 86      * 經過多個屬性查找,並分頁, 屬性名稱數組和屬性值數組的序列要對應
 87      * @param propertyNames 屬性名稱數組
 88      * @param values 屬性值數組
 89      * @param page 頁碼
 90      * @param pageSize 每頁內容條數
 91      * @return
 92      */
 93     public List<T> findByPropertys(String[] propertyNames, Object[] values, int page, int pageSize);
 94 
 95     /**
 96      * 經過屬性查找,並分頁, 屬性名稱數組和屬性值數組的序列要對應
 97      * @param propertyNames 屬性名稱
 98      * @param values 屬性值
 99      * @param page 頁碼
100      * @param pageSize 每頁內容條數
101      * @return
102      */
103     public List<T> findByProperty(String propertyName, Object value, int page, int pageSize);
104 
105     /**
106      * 查找並經過某一屬性排序
107      * @param property 排序依據的順序
108      * @param isSequence 是否順序排序
109      */
110     public List<T> findAndOrderByProperty(int firstResult, int fetchSize, String propertyName, boolean isSequence);
111 
112     /**
113      * 查找並經過某一屬性排序
114      * @param property  排序依據的順序
115      * @param isSequence 是否順序排序
116      */
117     public List<T> findAllAndOrderByProperty(String propertyName, boolean isSequence);
118 
119     /**
120      * 統計全部記錄的總數
121      * @return 總數
122      */
123     public int totalPage();
124 
125     /**
126      * 統計數據庫中當propertyName=value時的記錄總數
127      * @param propertyName
128      * @param value
129      * @return
130      */
131     public int totalPageByProperty(String propertyName, Object value);
132 
133     /**
134      * 統計數據庫中當多個propertyName=value時的記錄總數
135      * @param propertyNames
136      * @param values
137      * @return
138      */
139     public int totalPageByPropertys(String[] propertyNames, Object[] values);
140 
141 }

demo.loading.common.db   新建IBaseDao的實現類BaseDaoapache

  1 package demo.loading.common.db;
  2 
  3 import java.io.Serializable;
  4 import java.lang.reflect.ParameterizedType;
  5 import java.util.List;
  6 
  7 import javax.annotation.Resource;
  8 
  9 import org.hibernate.Query;
 10 import org.hibernate.SessionFactory;
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 13 import org.springframework.stereotype.Repository;
 14 
 15 
 16 /**
 17  * DAO的Hibernate基類
 18  * @param <T> pojo的類型
 19  * @para <ID> id的類型
 20  */
 21 @SuppressWarnings("all")
 22 public class BaseDao<T, ID extends Serializable> extends HibernateDaoSupport implements IBaseDao<T, ID> {
 23     
 24     @Resource    //把sessionfactory注入baseDao
 25     public void setMySessionFactory(SessionFactory sf) {
 26         super.setSessionFactory(sf);
 27     }
 28 
 29     private Class<T> persistentClass;
 30 
 31     public BaseDao() {
 32         // 獲取持久化對象的類型
 33         this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
 34     }
 35 
 36     /**
 37      * 得到持久化對象的類型
 38      * @return
 39      */
 40     public Class<T> getPersistentClass() {
 41         return persistentClass;
 42     }
 43 
 44     /**
 45      * 保存
 46      * @param entity 實體類
 47      */
 48     public void save(T entity) {
 49         this.getHibernateTemplate().save(entity);
 50     }
 51 
 52     /**
 53      * 刪除
 54      * @param entity  實體類
 55      */
 56     public void delete(T entity) {
 57         this.getHibernateTemplate().delete(entity);
 58     }
 59 
 60     /**
 61      * 與findByProperty類似,當properyName == value 時把相應的記錄刪除
 62      */
 63     public void deleteByProperty(String propertyName, Object value) {
 64         String queryString = "delete from " + getPersistentClass().getName() + " as model where model." + propertyName + "= ?";
 65         Query query = this.getSession().createQuery(queryString);
 66         query.setParameter(0, value);
 67         query.executeUpdate();
 68     }
 69 
 70     /**
 71      * 更新
 72      * @param entity
 73      */
 74     public void update(T entity) {
 75         this.getHibernateTemplate().update(entity);
 76     }
 77 
 78     /**
 79      * 保存或者更新
 80      * @param entity
 81      */
 82     public void saveOrUpdate(T entity) {
 83         this.getHibernateTemplate().saveOrUpdate(entity);
 84     }
 85 
 86     /**
 87      * 查詢全部
 88      * 
 89      */
 90     public List<T> findAll() {
 91         return this.getHibernateTemplate().find("from " + getPersistentClass().getName());
 92     }
 93 
 94     /**
 95      * 查找全部,並分頁
 96      * @param page 要返回的頁數
 97      * @param pageSize 沒有記錄數
 98      * @return
 99      */
100 
101     public List<T> findAll(int page, int pageSize) {
102         String queryString = "from " + getPersistentClass().getName();
103         Query query = this.getSession().createQuery(queryString);
104         int firstResult = (page - 1) * pageSize;
105         query.setFirstResult(firstResult);
106         query.setMaxResults(pageSize);
107         return query.list();
108     }
109 
110     /**
111      * 經過id查找
112      * @param id
113      * @return
114      */
115     public T findById(ID id) {
116         return (T) this.getHibernateTemplate().get(getPersistentClass(), id);
117     }
118 
119     /**
120      * find By Example
121      * @param entity
122      * @return
123      */
124     public List<T> findByExample(T entity) {
125         return this.getHibernateTemplate().findByExample(entity);
126     }
127 
128     /**
129      * 經過屬性查找
130      * @param propertyName  屬性名稱
131      * @param value  屬性的值
132      * @return
133      */
134     public List<T> findByProperty(String propertyName, Object value) {
135         String hql = "from " + getPersistentClass().getName() + " as model where model." + propertyName + "= ?";
136         return this.getHibernateTemplate().find(hql, value);
137 
138     }
139 
140     /**
141      * 經過多個屬性查找
142      * @param propertyNames 屬性名稱數組
143      * @param values 屬性值數組
144      * @return
145      */
146     public List<T> findByPropertys(String[] propertyNames, Object[] values) {
147         StringBuffer sb = new StringBuffer();
148         sb.append("from " + getPersistentClass().getName());
149         sb.append(" as model where ");
150         for (int i = 0; i < propertyNames.length; i++) {
151             if (i != 0)
152                 sb.append(" and");
153             sb.append(" model.");
154             sb.append(propertyNames[i]);
155             sb.append("=");
156             sb.append("? ");
157         }
158         String hql = sb.toString();
159         return this.getHibernateTemplate().find(hql, values);
160     }
161 
162     /**
163      * 經過多個屬性查找,並分頁, 屬性名稱數組和屬性值數組的序列要對應
164      * @param propertyNames 屬性名稱數組
165      * @param values  屬性值數組
166      * @param page 頁碼
167      * @param pageSize 每頁內容條數
168      * @return
169      */
170     public List<T> findByPropertys(String[] propertyNames, Object[] values, int page, int pageSize) {
171 
172         StringBuffer strBuffer = new StringBuffer();
173         strBuffer.append("from " + getPersistentClass().getName());
174         strBuffer.append(" as model where ");
175         for (int i = 0; i < propertyNames.length; i++) {
176             if (i != 0)
177                 strBuffer.append(" and");
178             strBuffer.append(" model.");
179             strBuffer.append(propertyNames[i]);
180             strBuffer.append("=");
181             strBuffer.append("? ");
182         }
183         String queryString = strBuffer.toString();
184 
185         int firstResult = (page - 1) * pageSize;
186 
187         Query query = this.getSession().createQuery(queryString);
188         query.setFirstResult(firstResult);
189         query.setMaxResults(pageSize);
190         for (int i = 0; i < values.length; i++) {
191             query.setParameter(i, values[i]);
192         }
193 
194         return query.list();
195     }
196 
197     /**
198      * 經過屬性查找,並分頁, 屬性名稱數組和屬性值數組的序列要對應
199      * @param propertyNames 屬性名稱
200      * @param values 屬性值
201      * @param page 頁碼
202      * @param pageSize 每頁內容條數
203      * @return
204      */
205     public List<T> findByProperty(String propertyName, Object value, int page, int pageSize) {
206         return this.findByPropertys(new String[] { propertyName }, new Object[] { value }, page, pageSize);
207     }
208 
209     /**
210      * 查找並經過某一屬性排序
211      * @param property 排序依據的順序
212      * @param isSequence 是否順序排序
213      */
214     public List<T> findAndOrderByProperty(int firstResult, int fetchSize, String propertyName, boolean isSequence) {
215         String queryString = "from " + getPersistentClass().getName() + " as model order by model." + propertyName;
216         if (isSequence == false) {
217             queryString = queryString + " DESC";
218         }
219 
220         Query queryObject = getSession().createQuery(queryString);
221         queryObject.setFirstResult(firstResult);
222         queryObject.setMaxResults(fetchSize);
223         return queryObject.list();
224 
225     }
226 
227     /**
228      * 查找並經過某一屬性排序
229      * @param property 排序依據的順序
230      * @param isSequence 是否順序排序
231      */
232     public List<T> findAllAndOrderByProperty(String propertyName, boolean isSequence) {
233         String queryString = "from " + getPersistentClass().getName() + " as model order by model." + propertyName;
234         if (isSequence == false) {
235             queryString = queryString + " DESC";
236         }
237 
238         Query queryObject = getSession().createQuery(queryString);
239         return queryObject.list();
240     }
241 
242     /**
243      * 統計全部記錄的總數
244      * @return 總數
245      */
246     public int totalPage() {
247         String queryString = "select count(*) from " + getPersistentClass().getName();
248         Query query = this.getSession().createQuery(queryString);
249         List list = query.list();
250         Long result = (Long) list.get(0);
251         return result.intValue();
252     }
253 
254     /**
255      * 統計數據庫中當propertyName=value時的記錄總數
256      * @param propertyName
257      * @param value
258      * @return
259      */
260     public int totalPageByProperty(String propertyName, Object value) {
261         String[] propertyNames = new String[] { propertyName };
262         Object[] values = new Object[] { value };
263         return this.totalPageByPropertys(propertyNames, values);
264     }
265 
266     /**
267      * 統計數據庫中當多個propertyName=value時的記錄總數
268      * @param propertyNames
269      * @param values
270      * @return
271      */
272     public int totalPageByPropertys(String[] propertyNames, Object[] values) {
273         StringBuffer strBuffer = new StringBuffer();
274         strBuffer.append("select count(*) from " + getPersistentClass().getName());
275         strBuffer.append(" as model where ");
276         for (int i = 0; i < propertyNames.length; i++) {
277             if (i != 0)
278                 strBuffer.append(" and");
279             strBuffer.append(" model.");
280             strBuffer.append(propertyNames[i]);
281             strBuffer.append("=");
282             strBuffer.append("? ");
283         }
284 
285         String queryString = strBuffer.toString();
286         Query query = this.getSession().createQuery(queryString);
287         for (int i = 0; i < values.length; i++) {
288             query.setParameter(i, values[i]);
289         }
290 
291         List list = query.list();
292         Long result = (Long) list.get(0);
293         return result.intValue();
294     }
295 
296 }

簡單的實現一個註冊登陸的方法
demo.loading.dao.idao  新建接口IUserDao
數組

 1 package demo.loading.dao.idao;
 2 
 3 import java.util.List;
 4 
 5 import demo.loading.common.db.IBaseDao;
 6 import demo.loading.entity.User;
 7 
 8 
 9 public interface IUserDao extends IBaseDao<User, String> {
10 
11     public List<User> login(String[] params, Object[] values);
12     
13 }

demo.loading.dao.imp 新建接口實現類UserDaosession

 1 package demo.loading.dao.imp;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.stereotype.Repository;
 6 
 7 import demo.loading.common.db.BaseDao;
 8 import demo.loading.dao.idao.IUserDao;
 9 import demo.loading.entity.User;
10 
11 @Repository("iUserDao")
12 //@Repository它用於將數據訪問層 (DAO 層 ) 的類標識爲 Spring Bean。
13 //爲了讓 Spring 可以掃描類路徑中的類並識別出 @Repository 註解,
14 //須要在 XML 配置文件中啓用Bean 的自動掃描功能
15 public class UserDaoImpl extends BaseDao<User, String> implements IUserDao {
16 
17     public List<User> login(String[] params, Object[] values) {
18         List<User> list = super.findByPropertys(params, values);
19         return list;
20     }
21 
22 }

demo.loading.test 新建 UserDaoImplTest 測試類app

 1 package demo.loading.test;
 2 
 3 import java.util.List;
 4 
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 import demo.loading.dao.idao.IUserDao;
10 import demo.loading.entity.User;
11 
12 public class UserDaoImplTest {
13     private static IUserDao userDao;
14     static{
15         String config = "applicationContext.xml";
16         ApplicationContext ac = new ClassPathXmlApplicationContext(config);
17         userDao = (IUserDao) ac.getBean("iUserDao");
18     }
19 
20     @Test
21     public void testLogin() {
22         String[] params = new String[] { "username", "password" };
23         Object[] values = new Object[] { "1009", "000000" };
24         List<User> users = userDao.findByPropertys(params, values);
25         for(User user : users){
26             System.out.println(user.getUsername());
27         }
28     }
29 
30 }

demo.loading.service.iservice 新建IUserService接口

1 package demo.loading.service.iservice;
2 
3 import java.util.List;
4 
5 import demo.loading.entity.User;
6 
7 public interface IUserService {
8     public List<User> login(String[] params, Object[] values);
9 }

demo.loading.service.impl 新建IUserService的實現類

 1 package demo.loading.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.springframework.stereotype.Repository;
 8 import org.springframework.stereotype.Service;
 9 import org.springframework.transaction.annotation.Transactional;
10 
11 import demo.loading.dao.idao.IUserDao;
12 import demo.loading.entity.User;
13 import demo.loading.service.iservice.IUserService;
14 
15 @Service    
16 //@Component 是一個泛化的概念,僅僅表示一個組件 (Bean) ,能夠做用在任何層次。
17 //@Service 一般做用在業務層,可是目前該功能與 @Component 相同。
18 @Transactional    
19 //配置事務 默認的增刪改查 @Transactional(readOnly=true) 查詢使用 只讀
20 @Repository("iUserService")
21 public class UserServiceImpl implements IUserService {
22 
23     @Resource IUserDao userDao;        //注入IUserDao
24     
25     public List<User> login(String[] params, Object[] values) {
26         return userDao.login(params, values);
27     }
28 }

demo.loading.test 新建UserServiceImplTest測試類

package demo.loading.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import demo.loading.entity.User;
import demo.loading.service.iservice.IUserService;

public class UserServiceImplTest {

    public static  IUserService userService;
    static {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        userService = (IUserService) ac.getBean("iUserService");
    }
    @Test
    public void testLogin() {
        String[] params = new String[] { "username", "password" };
        Object[] values = new Object[] { "1009", "000000" };
        List<User> users = userService.login(params, values);
        for(User user : users){
            System.out.println(user.getUsername());
        }
    }

}

------------------------------------------------------------------------------

hibernate+spring 整合完畢

------------------------------------------------------------------------------

整合struts2

Xml代碼

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 6     <display-name></display-name>
 7 
 8     <welcome-file-list>
 9         <welcome-file>login.jsp</welcome-file>
10     </welcome-file-list>
11 
12     <!-- 指定spring的配置文件,默認從web根目錄尋找配置文件,咱們能夠經過spring提供的classpath:前綴指定從類路徑下尋找 -->
13     <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <!-- 若是有多個文件 使用 "," 分開 -->
16         <param-value>classpath:applicationContext.xml</param-value>
17     </context-param>
18 
19     <listener>
20         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
21     </listener>
22 
23     <!-- 對spring容器進行實例化 -->
24     <listener>
25         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
26     </listener>
27 
28      <!--配置Struts2的過濾器 -->
29     <filter>
30         <filter-name>struts2filter</filter-name>
31         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
32     </filter>
33 
34     <filter-mapping>
35         <filter-name>struts2filter</filter-name>
36         <url-pattern>/*</url-pattern>
37     </filter-mapping>
38 
39 </web-app>

 

實現一個簡單的登陸

demo.loading.action 新建LoginAction

 1 package demo.loading.action;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 import javax.servlet.http.HttpServletRequest;
 7 
 8 import org.apache.struts2.interceptor.ServletRequestAware;
 9 import org.springframework.stereotype.Controller;
10 
11 import demo.loading.entity.User;
12 import demo.loading.service.iservice.IUserService;
13 
14 @Controller        //注入action
15 public class LoginAction implements ServletRequestAware {
16     @Resource IUserService userService;        //注入IUserService
17     private HttpServletRequest request;
18 
19     private User user;
20     private List<User> users;
21 
22     public String login() {
23         String username = request.getParameter("username");
24         String password = request.getParameter("password");
25         String[] params = new String[] { "username", "password" };
26         Object[] values = new Object[] { username, password };
27         users = userService.login(params, values);
28         if (users.isEmpty()) {
29             return "fail";
30         } else {
31             return "success";
32         }
33     }
34 
35     public void setServletRequest(HttpServletRequest request) {
36         this.request = request;
37     }
38 
39     public User getUser() {
40         return user;
41     }
42 
43     public void setUser(User user) {
44         this.user = user;
45     }
46 
47     public List<User> getUsers() {
48         return users;
49     }
50 
51     public void setUsers(List<User> users) {
52         this.users = users;
53     }
54 
55 }

 

struts.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 <struts>
 6     <!-- 把它設置爲開發模式,發佈時要設置爲false -->
 7     <constant name="struts.devMode" value="true" />
 8     <!-- 自動動態方法的調用,使用這個設置後能夠這樣調用:action!method -->
 9     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
10     <!-- 設置struts的對象工廠,由spring進行建立 (更換Struts2的工廠) -->
11     <constant name="struts.objectFactory" value="spring" />
12 
13     <package name="base-package" extends="struts-default">
14         <action name="loginAction" class="loginAction">
15             <result name="success">success.jsp</result>
16             <result name="fail">fail.jsp</result>
17         </action>
18     </package>
19 </struts>

------------------------------------------------------------------------------

整合完畢

------------------------------------------------------------------------------

login.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>登錄</title>
13 
14   </head>
15   
16   <body>
17    <form action="loginAction!login.action" method="post">
18        用戶名:<input type="text" name="username"><br>
19        密碼:<input type="password" name="password"><br>
20        <input type="submit" value="提交">
21    </form>
22   </body>
23 </html>

success.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>登陸成功</title>
13   </head>
14   
15   <body>
16     <span>登陸成功</span>
17   </body>
18 </html>

fail.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>登陸失敗</title>
13 
14   </head>
15   
16   <body>
17     登陸失敗
18   </body>
19 </html>

 

http://localhost:8080/demo/ 

進入測試頁面

相關文章
相關標籤/搜索