当然,对于annotation和xml风格的配置,谁更好,更多依赖个人兴趣。但使用annotation确实减少了很多配置工作量。本文采用annotation风格的配置,以TaskList为例子讲解struts2 spring hibernate的集成。项目文件见附件。
一:配置struts2。
首先在web.xml文件中配置filter Xml代码
1.
2.
3.
6.
7.
然后在classpath中创建struts.xml配置文件。 Xml代码
1.
2. 3. "http://struts.apache.org/dtds/struts-2.1.dtd"> 4.
5.
6.
7.
8.
10.
12.
13.
16.
struts.devMode属性,配置启用调试,将有更多的错误信息输出,便于排错。struts.convention.default.parent.package属性,指定使用注解标注的控制器的默认包。可以在这个默认包中配置全局信息。
struts.convention.package.locators属性,为查找控制器包路径的关键字。如com.mycompany.action,com.mycompany.action.user,都会被struts2扫描。里面有继承至Action的类,或类名以Action结尾的类,都会做为Action处理。
把struts2-spring-plugin-2.1.6.jar添加到classpath中,struts2会自动扫描struts-plugin.xml文件,该文件自动注册了
com.opensymphony.xwork2.ObjectFactory,完成和spring的集成。
二:配置spring
在web.xml中加入ContextLoaderListener,用以启动spring容器。用
contextConfigLocation指定spring配置文件路径,可以使用*通配符结尾。 Xml代码
1.
2.
3.
5.
6.
7.
8.
配置applicationContext.xml Xml代码
1. 2.
4.
6.
8.
10.
11.
12.
14.
15.
18.
19.
20.
然后定义了sessionFactory和transactionManager,hibernateTemplate用来注入到Dao中,取代继承的方式使用spring对hibernate的集成支持。
三:hibernate配置
hibernate配置独立配置,方便修改。 Xml代码
1.
2. 3.
5.
6.
7.
8.
9.
10.
11.
15.
16.
17.
18.
20.
21.
22.
23. 24.
25.
26.
27.
28.
30.
32.
四:TaskList Demo
详细代码查看附件,附件一使用maven构建。进入目录,使用mvn jetty:run启动项目,记住创建sshdemo mysql数据库。附件二为Eclipse项目,包含所有依赖包。