Java + Jersey + Gradle - java.sql.SQLException: 找不到合适的驱动程序

Java + Jersey + Gradle - java.sql.SQLException: No suitable driver found

SQL 在我正在开发的 Java WebApp 中工作时遇到问题。这似乎是球衣没有加载我的 sql 驱动程序的问题。

获取 java.sql.SQLException:当我调用我的端点时,没有找到适合 jdbc:h2:testDbName 的驱动程序。

注意:

  1. 连接字符串有效并且在不在 运行 时有效 Web 容器。

  2. gradle 脚本被配置为正确放置 sql 驱动程序(h2 在此 case) 在lib目录下

我已将代码简化为以下内容:

TestResource.java

@Path("/user")
public class TestResource {

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createForm(@FormParam("name") String name) throws Exception{

        Connection connection = DriverManager.getConnection("jdbc:h2:testDbName");
        connection.close();

        return Response.status(SC_ACCEPTED).build();
    }
}

build.gradle

apply plugin: 'war'

repositories {
    mavenCentral()
}

dependencies {
    compile 'javax.servlet:servlet-api:2.5'
    compile "javax.ws.rs:jsr311-api:1.1.1"
    compile 'com.sun.jersey:jersey-bundle:1.19'

    compile 'com.h2database:h2:1.3.175'
}

webapp.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <servlet>
        <servlet-name>Jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>testPackage</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

根据 peeskillet,显式加载驱动程序解决了问题。

@Path("/user")
public class TestResource {

    static{ DriverManager.registerDriver(new org.h2.Driver()) } 

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createForm(@FormParam("name") String name) throws Exception{

        Connection connection = DriverManager.getConnection("jdbc:h2:testDbName");
        connection.close();

        return Response.status(SC_ACCEPTED).build();
    }
}