【发布时间】:2019-06-16 19:32:12
【问题描述】:
我正在尝试使用 JNDI 方法连接我的 Microsoft sql 服务器。我的代码作为容器运行。详情如下
下面是我在 META-INF 下的 context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/CIBILDB"
auth="Container"
type="javax.sql.DataSource"
validationQuery="SELECT 1"
validationInterval="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
jmxEnabled="true"
username="automationrobot"
password="Soft2007"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://TGSLAP-2154\\SQLEXPRESS:1433"/>
</Context>
下面是我的java代码
package com.CIBIL.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class InitialiseCIBILDBConnection {
private static DataSource dataSource;
private static final String JNDI_LOOKUP_SERVICE = "java:/comp/env/jdbc/CIBILDB";
static{
try {
Context context = new InitialContext();
Object lookup = context.lookup(JNDI_LOOKUP_SERVICE);
if(lookup != null){
dataSource =(DataSource)lookup;
}else{
new RuntimeException("JNDI look up issue.");
}
} catch (NamingException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
当我使用上面的代码时,我得到了错误
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
有人可以帮我解决这个问题吗?
【问题讨论】:
-
您使用的是哪个服务器?某些服务器可能需要额外配置。
-
我使用 MS Sql Server 2014 作为数据库服务器和 Apache Tomcat 作为 Web 服务器