在tomcat上部署项目时,JDBC数据源无法正常工作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在tomcat上部署项目时,JDBC数据源无法正常工作相关的知识,希望对你有一定的参考价值。

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

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

配置信息:

  • OS:macOS High Sierra
  • tomcat版本:8.5
  • eclipse:Neon.2。,版本4.6.2
  • Java:8
  • MariaDB驱动程序:mariadb-java-client-2.2.0

在日食之外,司机在两个地方:

  • / Tomcat的文件夹/ lib中
  • / tomcat-folder / webapps / my-app / WEB-INF / lib(来自WAR文件)

我已将以下资源引用添加到应用程序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>

我已将以下资源添加到/tomcat-folder/contf/context.xml:

<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”/>

我得到的错误是:

java.sql.SQLException: Cannot create JDBC driver of class 'org.mariadb.jdbc.Driver' for connect URL 'jdbc:mariadb//localhost:3306/MYDB'
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at DBConfigTest.getConnection(DBConfigTest.java:123)
    at DBConfigTest.doGet(DBConfigTest.java:59)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: No suitable driver
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2158)
    ... 28 more
java.lang.NullPointerException
    at DBConfigTest.doGet(DBConfigTest.java:61)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

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

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

   // 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”。在mariadb之后和//之前的JDBC URL中的冒号(:)丢失了。

<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”/>

以上是关于在tomcat上部署项目时,JDBC数据源无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章

云服务器部署javaweb项目tomcat启动后页面无法正常跳转

Ktor 和远程 tomcat 部署

javaweb项目部署到linux的tomcat无法访问到,提示404.

tomcat 403 forbidden - 无法访问我在webapps中部署的项目

java,rsa加解密在本地正常,部署到tomcat上加解密后出现乱码。

java写了一个web项目 已经部署在tomcat上了 但是局域网内无法访问 怎么处理