【问题标题】:Name [jdbc/mydb] is not bound in this Context. Unable to find [jdbc]名称 [jdbc/mydb] 未绑定在此上下文中。找不到 [jdbc]
【发布时间】:2019-06-16 19:28:29
【问题描述】:

我的操作系统是 Windows 10。
我从https://tomcat.apache.org/download-90.cgi下载了Tomcat 9.0
我从https://www.eclipse.org/downloads/packages/release/2018-12/r/eclipse-ide-enterprise-java-developers下载了 Eclipse
我在外部服务器上使用 MySQL 5.5。
我从https://dev.mysql.com/downloads/connector/j/8.0.html下载了Connector/J 8.0
我使用 DriverManager 类成功连接到 MySQL 数据库。

现在我想使用Tomcat JNDI 建立数据库连接,但它不起作用。
Tomcat 安装在 C:\MyPrograms\Tomcat 中。
我的 Eclipse 工作区是 C:\Users\Felix\eclipse-workspace。

我将 JDBC 驱动程序 mysql-connector-java-8.0.13.jar 复制到 C:\MyPrograms\Tomcat\lib。

我的 C:\MyPrograms\Tomcat\conf\server.xml(没有 cmets):

<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
  <GlobalNamingResources>
    <Resource name="jdbc/mydb" global="jdbc/mydb" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" auth="Container" type="javax.sql.DataSource" username="felix1_0" password="mypassword" driverClassName="com.mysql.jdbc.Driver" description="mydb example" url="jdbc:mysql://192.168.88.88:3306/felix1_0" maxTotal="8" maxIdle="4" maxWaitMillis="10000" removeAbandonedTimeout="300" defaultAutoCommit="true"/>
  </GlobalNamingResources>
  <Service name="Catalina">
    <Connector port="9999" protocol="HTTP/1.1"
                URIEncoding="UTF-8"
                maxThreads="200"
                minSpareThreads="10"
                connectionTimeout="20000"
                redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

我的 C:\Users\Felix\eclipse-workspace\DynamicWebProjectTest\WebContent\WEB-INF\web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>DynamicWebProjectTest</display-name>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

    <resource-ref>
        <description>This is a reference to the global Resource for MySQL database connetion.</description>
        <res-ref-name>jdbc/mydb</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

我的 C:\Users\Felix\eclipse-workspace\DynamicWebProjectTest\WebContent\META-INF\context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context>
    <ResourceLink name="jdbc/mydb" global="jdbc/mydb" type="javax.sql.DataSource"/>
</Context>

我的 Servlet:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.ResultSet;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MyServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h3>Hello Eclipse</h3><br><br>");
        out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");

        try {
            establishJNDIDatabaseConnection(out);
        } catch (NamingException e) {
            out.println("<br>Error: NamingException: " + e.getMessage());
        } catch (SQLException e) {
            out.println("<br>Error: SQLException: " + e.getMessage());
        }
        out.println("</body></html>");
    }

    void establishJNDIDatabaseConnection(PrintWriter out) throws NamingException, SQLException {
        /*
         * Get initial context that has references to all configurations and 
         * resources defined for this web application. 
         */
        Context initialContext = new InitialContext();
        out.println("<br>Context initialContext = new InitialContext();");

        /*
         * Get Context object for all environment naming (JNDI), such as 
         * Resources configured for this web application. 
         */
        Context environmentContext = (Context) initialContext.lookup("java:comp/env");
        out.println("<br>Context environmentContext = (Context) initialContext.lookup(\"java:comp/env\");");

        /*
         * Get the DataSource for MySQL to request a connection
         */
        DataSource dataSource = (DataSource) environmentContext.lookup("jdbc/mydb");
        out.println("<br>DataSource dataSource = (DataSource) environmentContext.lookup(\"jdbc/mydb\");");

        /*
         * Request a Connection from the pool of connection threads
         */
        Connection con = dataSource.getConnection();
        out.println("<br>Connection con = dataSource.getConnection();");

        /*
         * Query the database
         */
        StringBuilder msg = new StringBuilder();
        try (Statement stm = con.createStatement()) {
            ResultSet rs = stm.executeQuery("SHOW TABLES;");
            while(rs.next()) {
                msg.append(rs.getString("Tables_in_felix1_0"));
            }
        } catch(SQLException e) {
            out.println("<br>Error: " + e.getMessage());
        } finally {
            if(con != null) {
                con.close();
            }
            con = null; //prevent future access
        }

        out.println("<br>Returned from SQL: " + msg.toString());
    }
}

错误:“NamingException:名称 [jdbc/mydb] 未绑定在此上下文中。无法找到 [jdbc]。”被这行代码抛出:

DataSource dataSource = (DataSource) environmentContext.lookup("jdbc/mydb");

我该如何解决这个问题?

【问题讨论】:

    标签: mysql eclipse tomcat jdbc jndi


    【解决方案1】:

    使用MySQL Connector/J 8.0.13useSSL的默认值为true。(https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-configuration-properties.html)。将server.xml中的JDBC URL修改为jdbc:mysql://192.168.88.88:3306/felix1_0?useSSL=false并重启tomcat。

    您还可以使用较低版本的 mysql 驱动程序(例如)mysql-connector-java-5.1.18-bin.jarjdbc:mysql://192.168.88.88:3306/felix1_0 JDBC URL。

    【讨论】:

    • 感谢您的回复,但这并没有解决我的问题。我已经使用 JDBC URL jdbc:mysql://192.168.88.88:3306/felix1_0 通过 DriverManager 类连接到数据库,并且一切正常。
    猜你喜欢
    • 2014-04-28
    • 2018-09-12
    • 2018-11-02
    • 2017-07-17
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2012-09-11
    相关资源
    最近更新 更多