日期:2014-05-16  浏览次数:20433 次

Struts+Spring+JDBC 简单配置

???? 项目需要,在原来Struts的基础上,配了Spring,数据库访问也用JDBC代替,由于Spring出色的控制反转,JDBC连接的工作基本上不需要考虑,只要专注于数据抽取就可以了,下边把代码贴一下,顺便说说一些小细节。

Spirng和Struts结合,主要有三种方式:
1,使用ActionSupport类
2,覆盖RequestProcessor
3,将Action委托给Spring
文章<使用 Spring更好地处理Struts动作> 中,对这三种方法都分析得比较详细,我在这里归纳一下.
使 用第一种方法,是最简单的,不需要其他任何配置,只需要在把继承Action,改成继承ActionSupport,带来的问题就是Struts与 Spring,紧耦合,以后不使用Spring配置时,需要修改代码.但其实,我目前觉得使用此方法,有一个好处是可以方便的得到 WebApplicationContext对象,不然,就需要使用ClassPathXmlApplicaiton("...")来取得Context 对象,不是很方便.其实,看DelegationActionUtils的源码,applicationContext对象也只是,这样子通过 sturts的plugin取得的.
actionServlet.getServletContext().getAttribute(
??? ??? ??? ??? ??? ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX + modulePrefix)

第二种方法,所有Action的分发都是通过ActionServlet的,而实际上的操作是由RequestProcessor 完成的,因此,可以把它覆盖,引入Spring
The RequestProcessor is where the majority of the core processing occurs for each request. Since version 1.3, the default Request Processor (ComposableRequestProcessor) is composed using Jakarta Commons Chain, which is an implementation of the Chain of Responsibility pattern (CoR).

The <controller> element allows you to configure the ActionServlet. Many of the controller parameters were previously defined by servlet initialization parameters in your web.xml file but have been moved to this section of struts-config.xml in order to allow different modules in the same web application to be configured differently.

第三种是最推荐的方法
顺便说一下,plugin在struts的概念,来自UserGuide:
The PlugIn interface extends Action and so that applications can easily hook into the ActionServlet lifecycle. This interface defines two methods, init() and destroy(), which are called at application startup and shutdown, respectively. A common use of a Plugin Action is to configure or load application-specific data as the web application is starting up.
其中Spring中的ContextLoaderPlugIn就是继承此PlugIn ,从而引入了Spring


基本上这样子就可以把Spring+Struts配置好,然后Spring+JDBC,关键就是配置好DataSource,然后通过JdbcTemplate类,就可以很方便的进行配置.以下部分为代码:

web.xml

< web-app >

?

????
< param-name > contextConfigLocation </ param-name >
????
<