张英泽 struts2+spring+hibernate整合步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<pre name= "code" class = "java" > 1 .<?xml version= "1.0" encoding= "UTF-8" ?> 
5 .    xsi:schemaLocation="http: //www.springframework.org/schema/beans 
6 .           http: //www.springframework.org/schema/beans/spring-beans-2.5.xsd 
7 .           http: //www.springframework.org/schema/context 
8 .           http: //www.springframework.org/schema/context/spring-context-2.5.xsd 
9 .           http: //www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
10 .           http: //www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
11
12 .    <!-- 将bean交由spring管理可以 用<bean></bean>和扫描加注 --> 
13 .    <!-- 
14 .        扫描该包及该包下的子包 
15 .    --> 
16 .    <context:component-scan base- package = "com.yss" ></context:component-scan> 
17
18
19 .    <!-- 集成hibernate  sessionFactory单例模式  线程安全  创建耗内存--> 
20 .    <!-- 将hibernate的事务也交由spring管理 --> 
21 .    <bean id= "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" 
22 .        destroy-method= "close"
23 .        <property name= "driverClass" value= "org.gjt.mm.mysql.Driver" /> 
24 .        <property name= "jdbcUrl" 
25 .            value= "jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8" /> 
26 .        <property name= "user" value= "root" /> 
27 .        <property name= "password" value= "root" /> 
28 .        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default:  3 --> 
29 .        <property name= "initialPoolSize" value= "1" /> 
30 .        <!--连接池中保留的最小连接数。--> 
31 .        <property name= "minPoolSize" value= "1" /> 
32 .        <!--连接池中保留的最大连接数。Default:  15 --> 
33 .        <property name= "maxPoolSize" value= "300" /> 
34 .        <!--最大空闲时间, 60 秒内未使用则连接被丢弃。若为 0 则永不丢弃。Default:  0 --> 
35 .        <property name= "maxIdleTime" value= "60" /> 
36 .        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default:  3 --> 
37 .        <property name= "acquireIncrement" value= "5" /> 
38 .        <!--每 60 秒检查所有连接池中的空闲连接。Default:  0 --> 
39 .        <property name= "idleConnectionTestPeriod" value= "60" /> 
40 .    </bean> 
41
42 .    <bean id= "sessionFactory" 
43 .         class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"
44 .        <property name= "dataSource" ref= "dataSource" /> 
45 .        <property name= "mappingResources" ><!-- 放置hibernate的配置文件 --> 
46 .            <list> 
47 .                <value>com/yss/bean/Employee.hbm.xml</value> 
48 .            </list> 
49 .        </property> 
50 .        <property name= "hibernateProperties"
51 .            <value> 
52 .                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect 
53 .                hibernate.hbm2ddl.auto=update 
54 .                hibernate.show_sql= true 
55 .                hibernate.format_sql= false 
56 .              </value> 
57 .        </property> 
58 .    </bean> 
59 .     
60 .    <!--hibernate事务管理器配置--> 
61 .    <bean id= "transactionManager" class = "org.springframework.orm.hibernate3.HibernateTransactionManager"
62 .        <property name= "sessionFactory" ref= "sessionFactory" ></property> 
63 .    </bean> 
64 .     
65 .    <!--spring可以用xml和注解来配置事务 声明  --> 
66 .    <tx:annotation-driven transaction-manager= "transactionManager" /> 
67 .</beans> 
  
    *配置hibernate的model.hbm.xml和创建model类
    *创建service
      service接口:
       
 
 
Java代码
1 . public interface EmployeeService { 
2 .     public boolean save(Employee employee); 
3 .     public boolean update(Employee employee); 
4 .     public Employee find(String username); 
5 .     public boolean delete(String... username); //表示可变参数 
6 .     public List<Employee> findAll(); 
7 .} 
  
      service实现类:
      
 
 
Java代码
1 . import java.util.List; 
2
3 . import javax.annotation.Resource; 
4
5 . import org.apache.log4j.Logger; 
6 . import org.hibernate.SessionFactory; 
7 . import org.springframework.stereotype.Service; 
8 . import org.springframework.transaction.annotation.Propagation; 
9 . import org.springframework.transaction.annotation.Transactional; 
10
11 . import com.yss.bean.Employee; 
12 . import com.yss.service.EmployeeService; 
13
14 . /**
15. * @author qing 默认bean名称 employeeServiceBean
16. *@Service @Transactional 注入service和开启事务
17. */ 
18 . @Service 
19 . @Transactional 
20 . public class EmployeeServiceBean  implements EmployeeService { 
21 .     private static Logger logger = Logger.getLogger(Employee. class ); 
22 .     /**
23.     * 注入sessionFactory
24.     */ 
25 .     @Resource SessionFactory factory; 
26
27 .     public boolean delete(String... usernames) { 
28 .         try
29 .             for (String username : usernames) { 
30 .                factory.getCurrentSession().delete( 
31 .                        factory.getCurrentSession().load(Employee. class
32 .                                username)); 
33 .            } 
34 .        }  catch (Exception e) { 
35 .            logger.error(e.getMessage()); 
36 .             return false
37 .        } 
38 .         return true
39 .    } 
40
41 .     /*
42.     * (non-Javadoc)
43.     * 
44.     * @see com.yss.service.EmployeeService#find(com.yss.bean.Employee)
45.     * 此标注表示不需要事务处理
46.     */ 
47 .     @Transactional (propagation = Propagation.NOT_SUPPORTED) 
48 .     public Employee find(String username) { 
49 .         return (Employee) factory.getCurrentSession().get(Employee. class
50 .                username); 
51 .    } 
52
53 .     @SuppressWarnings ( "unchecked"
54 .     @Transactional (propagation = Propagation.NOT_SUPPORTED) 
55 .     public List<Employee> findAll() { 
56 .         return factory.getCurrentSession().createQuery( "from Employee emp"
57 .                .list(); 
58 .    } 
59
60 .     public boolean save(Employee employee) { 
61 .         try
62 .            factory.getCurrentSession().persist(employee); // .save(employee);// 
63 .                                                             // 获取已经开好的Session 
64 .        }  catch (Exception e) { 
65 .            logger.error(e.getMessage()); 
66 .             return false
67 .        } 
68 .         return true
69 .    } 
70
71 .     public boolean update(Employee employee) { 
72 .         try
73 .            factory.getCurrentSession().merge(employee); // 类似于saveOrUpdate()方法 
74 .        }  catch (Exception e) { 
75 .            logger.error(e.getMessage()); 
76 .             return false
77 .        } 
78 .         return true
79 .    } 
80
81 .} 
  
      *新建测试类
        
 
 
Java代码
1 . public class EmployeeTest { 
2 .     private static EmployeeService employeeService; 
3
4 .     @BeforeClass 
5 .     public static void setUpBeforeClass()  throws Exception { 
6 .         try
7 .            ApplicationContext context =  new ClassPathXmlApplicationContext( 
8 .                     "beans.xml" ); 
9 .            employeeService = (EmployeeService) context 
10 .                    .getBean( "employeeServiceBean" ); 
11 .        }  catch (Exception e) { 
12 .            System.out.println(e.getMessage()); 
13 .        } 
14 .    } 
15
16 .     @Test 
17 .     public void createTable() { 
18 .         //new ClassPathXmlApplicationContext("beans.xml"); 
19 .    }; 
20 .     
21 .     @Test 
22 .     public void save() { 
23 .         boolean result=employeeService.save( new Employee( "long" , "long" )); 
24 .         if (result) { 
25 .            System.out.println( "保存成功。。。。。" ); 
26 .        } else
27 .            System.out.println( "保存出错...." ); 
28 .        } 
29 .    }; 
30
31 .     @Test 
32 .     public void delete() { 
33 .         boolean result=employeeService.delete( "long" ); 
34 .         if (result) { 
35 .            System.out.println( "删除成功。。。。。" ); 
36 .        } else
37 .            System.out.println( "删除出错...." ); 
38 .        } 
39 .    }; 
40
41 .     @Test 
42 .     public void update() { 
43 .         boolean result=employeeService.update(( new Employee( "qing" , "long" ))); 
44 .         if (result) { 
45 .            System.out.println( "更新成功。。。。。" ); 
46 .        } else
47 .            System.out.println( "更新出错...." ); 
48 .        } 
49 .    }; 
50
51 .     @Test 
52 .     public void findAll() { 
53 .        List<Employee> elist=employeeService.findAll(); 
54 .        Iterator itor=elist.iterator(); 
55 .         while (itor.hasNext()){ 
56 .            Employee emp=(Employee)itor.next(); 
57 .            System.out.println(emp.getPassword()); 
58 .        } 
59 .    }; 
60 .     
61 .     @Test 
62 .     public void find(){ 
63 .        Employee employee=employeeService.find( "qing" ); 
64 .        System.out.println(employee.getPassword()); 
65 .    } 
66 .} 
  
       *ok  没问题spring和hibernate整合完毕
        
        *再将struts2所需包加入lib中
        *创建struts.xml配置文件
        
 
 
Java代码
1 .<?xml version= "1.0" encoding= "UTF-8" ?> 
2 .<!DOCTYPE struts PUBLIC 
3 .     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
5 .<struts> 
6 .    <!-- 将struts的action交由spring管理  不在由struts的工厂介入 --> 
7 .    <constant name= "struts.objectFactory" value= "spring" /> 
8 .     
9 .    < package name= "employee" namespace= "/employee" extends = "struts-default"
10 .        <action name= "list" class = "employeeAction"
11 .            <result name= "success"
12 .                /WEB-INF/feapp/employee.jsp 
13 .            </result> 
14 .        </action> 
15 .         
16 .        <action name= "manager_*" class = "employeeManagerAction" method= "{1}"
17 .            <result name= "success"
18 .                /WEB-INF/feapp/employeeadd.jsp 
19 .            </result> 
20 .            <result name= "message"
21 .                /WEB-INF/feapp/result.jsp 
22 .            </result> 
23 .        </action> 
24 .    </ package
25 .</struts> 
  
          *在web.xml中加入
            
 
 
Java代码
1 .<?xml version= "1.0" encoding= "UTF-8" ?> 
2 .<web-app version= "2.4" xmlns= "http://java.sun.com/xml/ns/j2ee" 
4 .    xsi:schemaLocation="http: //java.sun.com/xml/ns/j2ee  
5 .    http: //java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
6
7 .    <!-- 
8 .        指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 
9 .    --> 
10 .    <context-param> 
11 .        <param-name>contextConfigLocation</param-name> 
12 .        <param-value>classpath:beans.xml</param-value><!-- 多个配置文件的写法  classpath:beans1.xml,classpath:beans2.xml,classpath:beans3.xml --> 
13 .    </context-param> 
14 .    <!-- 对Spring容器进行实例化 --> 
15 .    <listener> 
16 .        <listener- class >org.springframework.web.context.ContextLoaderListener</listener- class
17 .    </listener> 
18
19 .    <!-- struts2 的监听器 --> 
20 .    <filter> 
21 .        <filter-name>struts2</filter-name> 
22 .        <filter- class
23 .            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter- class
24 .    </filter> 
25 .    <filter-mapping> 
26 .        <filter-name>struts2</filter-name> 
27 .        <url-pattern>/*</url-pattern> 
28 .    </filter-mapping> 
29
30 .    <welcome-file-list> 
31 .        <welcome-file>index.jsp</welcome-file> 
32 .    </welcome-file-list> 
33 .</web-app> 
  
       *创建相关jsp和action
        
 
 
Java代码
1 . @Controller  @Scope ( "prototype"
2 . public class EmployeeManagerAction  extends ActionSupport { 
3 .     @Resource EmployeeService employeeService; 
4 .     private Employee employee; 
5 .         
6 .     public String addUI(){ 
7 .         //System.out.println("user come"); 
8 .         return SUCCESS; 
9 .    } 
10 .     
11 .     public String add(){ 
12 .         //System.out.println("--------------"); 
13 .         boolean result=employeeService.save(employee); 
14 .         //ActionContext.getContext().put("genders", Gender.values()); 
15 .         if (result){ 
16 .            ActionContext.getContext().put( "message" "保存成功!" ); 
17 .        } else
18 .            ActionContext.getContext().put( "message" "保存失败!" ); 
19 .        } 
20 .         return "message"
21 .    } 
22
23 .     public Employee getEmployee() { 
24 .         return employee; 
25 .    } 
26
27 .     public void setEmployee(Employee employee) { 
28 .         this .employee = employee; 
29 .    } 
30 .} 
</pre>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值