我有一个基于Java Servlets的webservice,它运行在Tomcat服务器上。 在我的Servlet中,我使用类似如下的数据库池:
envContext = new InitialContext();
DataSource ds = (DataSource) envContext.lookup( "java:/comp/env/jdbc/Database" );
con = ds.getConnection();
对于初始化,我在我的web.xml文件中有以下设置:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/Database</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
接下来是 context.xml,这似乎是关键的一步:
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for each web application -->
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/Database" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/configerror_db"/>
</Context>
我看到了很多关于这个错误的问题,但是我无法解决它。
首先我想解释一下,当我使用我的Linux机器时,我没有遇到这个错误。然而,当我在我的Windows机器上使用Eclipse安装了相同的代码时,我就会遇到这个上下文环境错误。
其他答案建议这样做。
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"<initialContextFactory>");
env.put(Context.PROVIDER_URL, "<url>");
env.put(Context.SECURITY_PRINCIPAL, "<user>");
env.put(Context.SECURITY_CREDENTIALS, "<password>");
ctx = new InitialContext(env);
但是我不知道什么是initialContextFactory,而且context.xml难道不应该做这件事吗?就像我在Linux上说的那样,它可以工作。
有人能帮我解决一下吗?我错过了什么?我不想在每个使用数据库连接的文件中编写用户名和密码。我认为这很棒。凭据只需在context.xml中,但现在在Windows上它不起作用。
感谢任何建议。