一直想在SPRING中使用JNDI提供数据源,今天正好有些空闲时间整了下,使用TOMCAT5.5.26做为运行容器,发现其中问题还真不少,少一点配置就
会导至问题出现,以下是偶配置成功的经历,当然在学习之前你需要了解 SPRING、HIBERNATE、STRUTS或SERVLET或其它一些MVC应用框架,本文并
不会对这些框架进行介绍
注: 以下的%TOMCAT_HOME% 为 TOMCAT 的安装目录,以下分为六步来进行介绍及配置
本文使用的框架版本为 SPRING2.5 + HIBERNATE3.2
1、首先需要新建一个web 工程起名叫 sprintJndiTest,接下来开始着手配置
2、将 SQLServer 2000(当然也可以其它数据库驱动,根据自身设置)的JDBC驱动拷到%TOMCAT_HOME%/common/lib 目录
3、在%TOMCAT_HOME%/conf/server.xml 文件中的<Service> 元素中添加如下代码:
其中 /springJndiTest 是发布到TOMCAT中的工程映射名称,一定要一样, jdbc/ds 是自定义的一个JNDI名称,外部通 过此名称进行调用获取数据源信息
<Context path="/springJndiTest" docBase="springJndiTest" debug="0" reloadable="true" crossContext="true"> <Resource name="jdbc/ds" auth="Container" type="javax.sql.DataSource"/> <ResourceParams name="jdbc/ds"> <parameter> <name>driverClassName</name> <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value> </parameter> <parameter> <name>url</name> <value>jdbc:microsoft:sqlserver://localhost:1433;databaseName=test;selectMethod=cursor</value> </parameter> <parameter> <name>username</name> <value>sa</value> </parameter> <parameter> <name>password</name> <value>sa</value> </parameter> <parameter> <name>maxWait</name> <value>5000</value> </parameter> <parameter> <name>maxActive</name> <value>4</value> </parameter> </ResourceParams> </Context>
4、在%TOMCAT_HOME%/conf/Catalina/localhost/ 下新建一个与web 工程同名的xml 文件,我这就叫 springJndiTest.xml,在文件中添加如下内容:
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/ds" type="javax.sql.DataSource" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test;selectMethod=cursor" username="sa" password="sa" maxIdle="2" maxWait="5000" maxActive="4"/> </Context>
其中内属性值要与配置的 server.xml 中相对应,没有配置该文件将会出现导至下列二个异常的产生:
1、ERROR main org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jndiDataSource' defined in
ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
2、org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
5、此步并不是必须,网上很多资料都有添加此步,但我在使用过程中并没添加此步,还是把内容说下吧,在web工程的WEB-INF/web.xml 中添加如下内容:
<resource-ref> <res-ref-name>jdbc/ds</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
内容要与在TOMCAT中配置的server.xml相对应上
6、现在可以进行spring配置了,不多说了,把配置内容直接贴出来吧!相信了解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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/ds</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.spring25.hibernate.Users</value> <value>com.spring25.hibernate.Job</value> </list> </property> </bean> <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> <property name="cacheQueries" value="true"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 事务处理 --> <aop:config> <aop:pointcut id="servicePointcut" expression="execution(* com.spring25.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/> </aop:config> <!-- 事务控制,描述方法需要什么样的事务处理 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="login*" read-only="true"/> </tx:attributes> </tx:advice> <bean id="loginDao" class="com.spring25.dao.impl.LoginDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <bean id="loginService" class="com.spring25.service.impl.LoginService"> <property name="loginDao" ref="loginDao"/> </bean> </beans>
好了基本上的配置内容就是这些,本示例以经过测试,当然如果你需要测试也可以建立一个JSP来进行测试,如下:
<%@ page language="java" import="javax.naming.*,javax.sql.*,java.sql.*" contentType="text/html; charset=gb2312"%> <html> <head> <title>Test Jndi DataSource</title> </head> <body> <% Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Context initCtx = new InitialContext(); // 注意此处的java:comp/env 是tomcat 中估有的一个名称字符串 // 跟在后面的就是自定义的那个jndiname,每个容器的调用都会有不同,jboss 是 java/ DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/springJndiTest"); if (ds != null) { conn = ds.getConnection(); ps = conn.prepareStatement("select * from users"); rs = ps.executeQuery(); %> <table border=1> <tr> <td>uid</td> <td>userName</td> <td>password</td> <td>sex</td> <td>birthday</td> </tr> <% while (rs.next()) { %> <tr> <td><%=rs.getInt("uid")%></td> <td><%=rs.getString("username")%></td> <td><%=rs.getString("password")%></td> <td><%=rs.getString("sex")%></td> <td><%=rs.getString("birthday")%></td> </tr> <%} conn.close(); } } catch (Exception e) { e.printStackTrace(); } %> </body> </html>
当编写好后,启动容器,在浏览器中输入 http://localhost:8090/springJndiTest/ 出现结果正确说明配置成功
如果还有什么疑问或问题可直接加本人QQ:543997732 和本人创建的一个JavaEE群63267818 进行讨论