struts2.0+spring2.5+JDBC 连接数据库

前段时间尝试用 struts2.0+spring2.5+JDBC  连接数据库,开始怎样也搞不清在Spring里面怎样配置JDBC ,几经辛苦,终于学会了,而且明白了为什么要这样配置。在此和大家分享一下。

Spring 这东西是用来控制业务逻辑的。要配置的话,首先要导包,至于要导哪些包,我会在另外一篇文章里面写到,其实,我自己配的时候也是按照别人的文章说的步骤来配置的。所以,没什么好说。

事不宜迟,来看看 Spring 的配置文档是怎样写的,在Spring 的例子里找到ApplicationContext.xml (在哪里?用windows搜索一下 Spring   的目录就好了。)找到后,复制到自己的工程下,把多余的东西删掉,只留下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-lazy-init="true">
 
 

// 具体设置在这里

 

</beans>

然后,把以下代码复制到这个xml文件里面,就好了,Spring 对 JDBC 的支持就算配好了。



   
    
    <!-- Jdbc 事务控制器-->
 <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource"/>
 </bean>
 
<!-- 数据库连接配置 -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:microsoft:sqlserver://localhost:1433;database='BSOA'"></property>
<property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"></property>
<property name="username" value="ydManager"></property>
<property name="password" value="ydManager"></property>
</bean>

然后在你的工程里面创建一个实现 "dataSourceTransactionManager 的类,我这里 的类是“connectImp”  再把那个类里面的属性con 通过dataSourceTransactionManager 进行注入。具体配置如下:

  <bean id="connectImp" class="com.yd.workstation.contorls.DB_Connection">
    <property name="con" ref="dataSourceTransactionManager"></property>
    </bean>
    然后创建一个Action 也把Action 配置到 ApplicationContext.xml 里面。具体代码如下:

 <bean id="sqlcon" class="com.yd.workstation.struts.LoginAction">
    <property name="sqlcon" ref="connectImp"></property>
    </bean

这个类里面有一个属性,sqlcon,是com.yd.workstation.contorls.DB_Connection 类的,所以要通过上面的connectImp来注入,这样,一层一层地注入,把业务,数据操作,视图分开了,实现了MVC 模型。

由于我是初学,所以很多东西都说不清楚,大家不要见怪。

posted on 2009-03-12 20:37 流浪汉 阅读(1801) 评论(0)  编辑 收藏 引用 所属分类: javaweb

只有注册用户登录后才能发表评论。
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

公告

请你看完我的博客后,留下你对你看的日志或文章的一些意见和建议。

常用链接

留言簿

随笔分类

随笔档案

文章分类

新闻档案

相册

软件开发技术

搜索

最新评论

阅读排行榜

评论排行榜