1、新建项目 结构如下:
2、导入相关的jar
3、整合步骤先整合 Spring2.5+Hibernate3.3 成功后在整合 Struts2 这样就不容易报错,而且 报错误后也便于找出问题。
applicationContext.xml
spring配置文件模版可以到 spring自带的一些例子中进行拷贝。
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 数据库相关配置的信息
demo.loading.entity 新建实体User
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的实现类BaseDao
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 新建接口实现类UserDao
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 测试类
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/
进入测试页面