建议用Tomcat的Adiminstration添加。在默认情况下,Tomcat没有安装administration组件,详细安装步骤请参考《Install the component Admin for tomcat》。
登陆http://localhost:8080/admin, 进入Resources -> Data Sources -> Create New Data Source
设置JNDI参数:(这里以MySql为例)
JNDI Name:jdbc/mysql(JNDI 名随便起)
Data Source URL:jdbc:mysql://localhost:3306/test(这里test是数据库名,当然后面还可以带其他参数,如:jdbc: mysql://localhost:3306/test?user=root&password=&useUnicode=true& characterEncoding=gbk&autoReconnect=true&failOverReadOnly=false)
JDBC Driver Class:com.mysql.jdbc.Driver (要把相应的驱动jar包放到$TOMCAT_HOME$/common/lib)
User Name:root (用户名)
Password:***** (密码)
Max. Active Connections:4
Max. Idle Connections:2
Max. Wait for Connection:5000
Tomcat/conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="admin" password="admin" roles="admin,manager"/>
</tomcat-users>
Tomcat/conf/server.xml
<Resource
name="fcDataSource"
type="javax.sql.DataSource"
username="ecfcdb"
password="ecfcdb"
driverClassName="weblogic.jdbc.sqlserver.SQLServerDriver"
maxIdle="1"
maxWait="5000"
url="jdbc:bea:sqlserver://127.0.0.1:1433;DatabaseName=ecfcdb"
maxActive="1"/>
项目web.xml
<resource-ref>
<description>fc DB Connection</description>
<res-ref-name>fcDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在java代码中使用JNDI资源获得DataSource
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");
Connection conn = ds.getConnection();
该代码在JDK1.5下测试通过
在一些资料中提到,在JDK1.5以前的版本可以通过
DataSource ds = (DataSource) ctx.lookup("jdbc/mysql");
获得DataSource。
我没测试过该代码。
上述代码在J2EE服务器环境下工作得很好,但是在main()中就会报一个NoInitialContextException。
之所以有NoInitialContextException是因为无法从System.properties中获得必要的JNDI参数,在服务器环境下,服务器启动时就把这些参数放到System.properties中。
所以可以通过以下方法解决:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL,"t3://localhost:7001");
InitialContext ctx = new InitialContext(env);
或
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
System.setProperty(Context.PROVIDER_URL, "rmi://localhost:3306/test");
System.setProperty(Context.SECURITY_PRINCIPAL, "root");
System.setProperty(Context.SECURITY_CREDENTIALS, "123456");
以上代码建议改为在配置文件中配置
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.provider.url=rmi://localhost:3306/test
java.naming.security.principal=user
java.naming.security.credentials=password