名称[jdbc / mydb]在此上下文中未绑定。找不到[jdbc]

时间:2019-01-23 08:54:31

标签: mysql eclipse tomcat jdbc jndi

我的操作系统是Windows10。
我从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(不带注释):

<?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");

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

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

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