无法在我正在处理的Java WebApp中使用SQL。这似乎是泽西没有加载我的SQL驱动程序的问题。
获取 java.sql.SQLException:当我调用我的端点时,找不到合适的jdbc驱动程序:h2:testDbName 。
请注意:
连接字符串有效,并且在未运行时有效 Web容器。
gradle脚本配置为正确放置sqldriver(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>
答案 0 :(得分:0)
根据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();
}
}