我正在尝试在 ntellij idea 14 中使用 Tomcat 数据源和 MySQL 获取连接池。我已经完成了以下步骤:
从文件菜单中选择“项目结构”
从那里,选择“构面”选项。确保您已配置 Web 构面。如果没有,请添加一个。
添加 Web 构面后,选择“添加应用程序服务器特定描述符...”
从选项中选择 Tomcat 上下文描述符,然后单击确定。
我在 web 目录中获得了 META-INF/context.xml。我在 context.xml 中添加了下一行
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/payments"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/paymentsdb"
username="root"
password="password"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000"/>
</Context>
并将其放入 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--DB Connection start-->
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/payments</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
这是我获得连接的方法
public static Connection createConnection(){
Context context = null;
DataSource dataSource = null;
Connection connection = null;
try {
context = (Context) new InitialContext().lookup("java:comp/env");
dataSource = (DataSource) context.lookup("jdbc/payments");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
我得到了这个例外
dataSource = (DataSource) context.lookup("java:comp/env/jdbc/payments");
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
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at ua.epam.kuts.dao.MySQLDAOFactory.createConnection(MySQLDAOFactory.java:22)
at Test.main(Test.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
我使用 Tomcat 8.0.23。任何想法?我用谷歌搜索了几个小时,没有找到任何对我有帮助的东西。把我给气疯了。我检查了与Statment的连接并且它有效。我有connector.jar。