Java 在tomcat上部署项目时JDBC数据源不工作

Java 在tomcat上部署项目时JDBC数据源不工作,java,mysql,eclipse,tomcat,mariadb,Java,Mysql,Eclipse,Tomcat,Mariadb,我开发了一个servlet,它通过JDNI数据源调用MariaDB数据库。当我在eclipse中运行的tomcat服务器上运行eclipse中的web项目时,这很好 但是,当我使用WAR文件在eclipse外部的tomcat服务器上部署项目时,同一个servlet不起作用。出于测试目的,该项目还包含另一个直接连接的servlet,即不使用JDNI数据源连接到同一个mariaDB,即使部署到eclipse外部的tomcat服务器上,它也可以正常工作。 关于什么可能是错误的,我已经没有什么想法了,如

我开发了一个servlet,它通过JDNI数据源调用MariaDB数据库。当我在eclipse中运行的tomcat服务器上运行eclipse中的web项目时,这很好

但是,当我使用WAR文件在eclipse外部的tomcat服务器上部署项目时,同一个servlet不起作用。出于测试目的,该项目还包含另一个直接连接的servlet,即不使用JDNI数据源连接到同一个mariaDB,即使部署到eclipse外部的tomcat服务器上,它也可以正常工作。 关于什么可能是错误的,我已经没有什么想法了,如果有人能解释一下,我将不胜感激

配置信息:

OS:macOS High Sierra tomcat版本:8.5 eclipse:Neon.2.,第4.6.2版 爪哇:8 MariaDB驱动程序:MariaDB-java-client-2.2.0 在eclipse之外,驱动程序位于两个位置:

/tomcat文件夹/lib /WAR文件中的tomcat文件夹/webapps/my-app/WEB-INF/lib 我已将以下资源引用添加到应用程序web.xml文件:

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/MYDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
servlet代码如下所示:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBConfigTest extends HttpServlet{
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      // JDBC driver name and database URL
     // static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";  
     // static final String DB_URL="jdbc:mariadb://localhost/MYDB"+"?user=root&password=";

      //  Database credentials
     // static final String USER = "root";
     // static final String PASS = "";

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Database Result";

      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

      out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" +
         "<h1 align = \"center\">" + title + "</h1>\n");

   // Execute SQL query
      //Statement stmt=null;
      //Connection conn=null;
      Connection connection=null;
      PreparedStatement statement=null;

      try {
         // Register JDBC driver
         //Class.forName("org.mariadb.jdbc.Driver");

         // Open a connection
         //conn = DriverManager.getConnection("jdbc:mariadb://localhost/MYDB"+"?user=root&password=");

                connection = getConnection();
              String sql = "SELECT * FROM  ingredient";
              statement = connection.prepareStatement(sql);
              ResultSet rs = statement.executeQuery();

         // Execute SQL query
         /*stmt = conn.createStatement();
         String sql;
         sql = "SELECT * FROM  ingredient";
         ResultSet rs = stmt.executeQuery(sql);*/

         // Extract data from result set
         while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("ingredient_id");
            String code = rs.getString("ingredient_code");
            String description = rs.getString("ingredient_description");

            //Display values
            out.println("ID: " + id + "<br>");
            out.println(", Code: " + code + "<br>");
            out.println(", Description: " + description + "<br>");

         }
         out.println("</body></html>");

         // Clean-up environment
         rs.close();
         statement.close();
         connection.close();
      } catch(SQLException se) {
         //Handle errors for JDBC
         se.printStackTrace();
      } catch(Exception e) {
         //Handle errors for Class.forName
         e.printStackTrace();
      } finally {
         //finally block used to close resources
         try {
            if(statement!=null)
               statement.close();
         } catch(SQLException se2) {
         } // nothing we can do
         try {
            if(connection!=null)
            connection.close();
         } catch(SQLException se) {
            se.printStackTrace();
         } //end finally try
      } //end try
   }



   private Connection getConnection() {
        Connection connection = null;
        try {
          /*InitialContext context = new InitialContext();
          DataSource dataSource = (DataSource) context.lookup("jdbc/MYDB");
          connection = dataSource.getConnection();*/

            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource)envContext.lookup("jdbc/MYDB");
            connection = ds.getConnection();


        } catch (NamingException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        }
        return connection;
      }
}

下面示例中的url应为url=jdbc:mariadb://localhost:3306/MYDB”. 一个冒号:在JDBCURL中,在mariadb之后和//之前,缺少

<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
               url="jdbc:mariadb//localhost:3306/MYDB”/>

你确定org.mariadb.jdbc.Driver在类路径上吗?你在jdbc URL中缺少一个冒号:在mariadb之后和//之前。嗨,Steve和Andreas,谢谢你的快速回答。应用安德烈亚斯的答案解决了我的问题。我刚刚在tomcat服务器的context.xml中添加了:in。tomcat动态地考虑了这一点,并修复了资源定义的问题。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBConfigTest extends HttpServlet{
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      // JDBC driver name and database URL
     // static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";  
     // static final String DB_URL="jdbc:mariadb://localhost/MYDB"+"?user=root&password=";

      //  Database credentials
     // static final String USER = "root";
     // static final String PASS = "";

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Database Result";

      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

      out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" +
         "<h1 align = \"center\">" + title + "</h1>\n");

   // Execute SQL query
      //Statement stmt=null;
      //Connection conn=null;
      Connection connection=null;
      PreparedStatement statement=null;

      try {
         // Register JDBC driver
         //Class.forName("org.mariadb.jdbc.Driver");

         // Open a connection
         //conn = DriverManager.getConnection("jdbc:mariadb://localhost/MYDB"+"?user=root&password=");

                connection = getConnection();
              String sql = "SELECT * FROM  ingredient";
              statement = connection.prepareStatement(sql);
              ResultSet rs = statement.executeQuery();

         // Execute SQL query
         /*stmt = conn.createStatement();
         String sql;
         sql = "SELECT * FROM  ingredient";
         ResultSet rs = stmt.executeQuery(sql);*/

         // Extract data from result set
         while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("ingredient_id");
            String code = rs.getString("ingredient_code");
            String description = rs.getString("ingredient_description");

            //Display values
            out.println("ID: " + id + "<br>");
            out.println(", Code: " + code + "<br>");
            out.println(", Description: " + description + "<br>");

         }
         out.println("</body></html>");

         // Clean-up environment
         rs.close();
         statement.close();
         connection.close();
      } catch(SQLException se) {
         //Handle errors for JDBC
         se.printStackTrace();
      } catch(Exception e) {
         //Handle errors for Class.forName
         e.printStackTrace();
      } finally {
         //finally block used to close resources
         try {
            if(statement!=null)
               statement.close();
         } catch(SQLException se2) {
         } // nothing we can do
         try {
            if(connection!=null)
            connection.close();
         } catch(SQLException se) {
            se.printStackTrace();
         } //end finally try
      } //end try
   }



   private Connection getConnection() {
        Connection connection = null;
        try {
          /*InitialContext context = new InitialContext();
          DataSource dataSource = (DataSource) context.lookup("jdbc/MYDB");
          connection = dataSource.getConnection();*/

            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource)envContext.lookup("jdbc/MYDB");
            connection = ds.getConnection();


        } catch (NamingException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        }
        return connection;
      }
}
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
               url="jdbc:mariadb//localhost:3306/MYDB”/>