org.springframework.jdbc.CannotGetJdbcConnectionException,嵌套异常是java.sql.SQLException

huangapple go评论91阅读模式
英文:

org.springframework.jdbc.CannotGetJdbcConnectionException, nested exception is java.sql.SQLException

问题

我正在尝试使用Spring框架和Spring Security构建一个简单的CRUD应用程序应用程序有一个登录要求其中应用程序对用户进行授权和身份验证我能够使用硬编码的值进行登录但是当我尝试使用JDBC和MySQLWorkbench获取用户和密码时出现以下错误

`org.springframework.jdbc.CannotGetJdbcConnectionException: 无法获取JDBC连接嵌套异常是java.sql.SQLException无法从底层数据库获取连接!`

我尝试在测试类中进行调试它显示连接成功”。

```java
package com.paras.springsecurity.demo.config;

import java.sql.Connection;
import java.sql.DriverManager;

public class TestApp {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_security_demo_plaintext?useSSL=false", "springstudent", "springstudent");
            System.out.println("连接成功!!!!");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

现在我无法理解当应用程序和JDBC连接、密码和用户正常工作时出现了什么问题。

持久性MySQL属性 - persistence-mysql.properties

#
# JDBC连接属性
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_security_demo_plaintext?useSSL=false
jdbc.user=springstudent
jdbc.password=springstudent

#
# 连接池属性
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000

pom.xml

<!-- 在这里是pom.xml的内容,已省略 -->

JDBC配置文件 - DemoAppConfig.java

// 在这里是DemoAppConfig.java的内容,已省略

在类中调用Spring Security数据源 - DemoSecurityConfig.java

// 在这里是DemoSecurityConfig.java的内容,已省略

<details>
<summary>英文:</summary>
I am trying to build simple CRUD app with Spring framework and Spring security. There is a &#39;sign in&#39; requirement where app authorise and authenticates user. I was able to sign in with hard coded values but when I tried getting users and passwords with JDBC and MySQLWorkbench, its giving this error:
`org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!`
I tried debugging in a test Class and it gave &quot;connection successful&quot;
package com.paras.springsecurity.demo.config;
import java.sql.Connection;
import java.sql.DriverManager;
public class TestApp {
public static void main(String[]args){
Connection con = null;
try {
con = DriverManager.
getConnection(&quot;jdbc:mysql://localhost:3306/spring_security_demo_plaintext?useSSL=false&quot;, &quot;springstudent&quot;, &quot;springstudent&quot;);
System.out.println(&quot;Connection is successful !!!!!&quot;);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Now I am not able to understand what is the issue here when app and jdbc connections, password, and user is working
persistence-mysql.properties
#
# JDBC connection properties
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_security_demo_plaintext?useSSL=false
jdbc.user=springstudent
jdbc.password=springstudent
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
pom.xml
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.paras&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-demo&lt;/artifactId&gt;
&lt;version&gt;1.0&lt;/version&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;name&gt;spring-security-demo&lt;/name&gt;
&lt;properties&gt;
&lt;springframework.version&gt;5.2.8.RELEASE&lt;/springframework.version&gt;
&lt;springsecurity.version&gt;5.3.4.RELEASE&lt;/springsecurity.version&gt;
&lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;
&lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;!-- Spring MVC support --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;${springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Servlet, JSP and JSTL support --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;3.1.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
&lt;version&gt;2.3.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;jstl&lt;/artifactId&gt;
&lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- to compensate for java 9+ not including jaxb --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
&lt;version&gt;2.3.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;3.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- Spring security dependency --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
&lt;version&gt;5.3.4.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
&lt;version&gt;5.3.4.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Add support for spring security Taglib support --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-taglibs&lt;/artifactId&gt;
&lt;version&gt;5.3.4.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!--  Add mysql and c3p0 support --&gt;
&lt;dependency&gt;
&lt;groupId&gt;mysql&lt;/groupId&gt;
&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
&lt;version&gt;5.1.45&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.mchange&lt;/groupId&gt;
&lt;artifactId&gt;c3p0&lt;/artifactId&gt;
&lt;version&gt;0.9.5.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;!-- TO DO: Add support for Maven WAR Plugin --&gt;
&lt;build&gt;
&lt;finalName&gt;spring-security-demo&lt;/finalName&gt;
&lt;pluginManagement&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;!-- Add maven coordinates(GAV) for: maven-war-plugin --&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
&lt;version&gt;3.3.1&lt;/version&gt;					
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/pluginManagement&gt;
&lt;/build&gt;
&lt;/project&gt;
Jdbc configuration file - DemoAppConfig.java
package com.paras.springsecurity.demo.config;
import java.beans.PropertyVetoException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages=&quot;com.paras.springsecurity.demo&quot;)
@PropertySource(&quot;classpath:persistence-mysql.properties&quot;)
public class DemoAppConfig {
//set up a var to hold the projects
@Autowired
private Environment env;
//env will hold data read from proprties file
//set up a logger
private Logger logger = Logger.getLogger(getClass().getName());
//define a bean for viewResolver
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(&quot;/WEB-INF/view/&quot;);
viewResolver.setSuffix(&quot;.jsp&quot;);
return viewResolver;
}
//define a bean for our security datasource
@Bean
public DataSource securityDataSource() {
//create a connection pool
ComboPooledDataSource securityDataSource = new ComboPooledDataSource();
//set the jdbc driver class
try {
securityDataSource.setDriverClass(env.getProperty(&quot;jdbc.driver&quot;));
} catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
//log the connection props
logger.info(&quot;&gt;&gt;&gt;&gt;&gt; jdbc.url &quot; + env.getProperty(&quot;jdbc.url&quot;)); 
logger.info(&quot;&gt;&gt;&gt;&gt;&gt; jdbc.user &quot; + env.getProperty(&quot;jdbc.user&quot;)); 
//set database connection props
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.url&quot;));
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.user&quot;));
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.password&quot;));
//set connection pool props
securityDataSource.setInitialPoolSize(getIntProperty(&quot;connection.pool.initialPoolSize&quot;));
securityDataSource.setMinPoolSize(getIntProperty(&quot;connection.pool.minPoolSize&quot;));
securityDataSource.setMaxPoolSize(getIntProperty(&quot;connection.pool.maxPoolSize&quot;));
securityDataSource.setMaxIdleTime(getIntProperty(&quot;connection.pool.maxIdleTime&quot;));
return securityDataSource;
}
//helper method to read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
}
Calling Spring Security Data Source in the class - DemoSecurityConfig.java
package com.paras.springsecurity.demo.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
//add a reference  to our security source
@Autowired
private DataSource securityDataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers(&quot;/&quot;).hasRole(&quot;EMPLOYEE&quot;)
.antMatchers(&quot;/leaders/**&quot;).hasRole(&quot;MANAGER&quot;)
.antMatchers(&quot;/systems/**&quot;).hasRole(&quot;ADMIN&quot;)
.and().formLogin().loginPage(&quot;/showMyLoginPage&quot;)
.loginProcessingUrl(&quot;/authenticateTheUser&quot;).permitAll().and().logout().permitAll().and().exceptionHandling().
accessDeniedPage(&quot;/access-denied&quot;);
}
}
</details>
# 答案1
**得分**: 1
这是问题所在:
//设置数据库连接属性
securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setJdbcUrl(env.getProperty("jdbc.user"));
securityDataSource.setJdbcUrl(env.getProperty("jdbc.password"));
你在所有地方都使用了 setJdbcUrl。
应该像这样:
//设置数据库连接属性
securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setUser(env.getProperty("jdbc.user"));
securityDataSource.setPassword(env.getProperty("jdbc.password"));
<details>
<summary>英文:</summary>
Here is the issue
//set database connection props
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.url&quot;));
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.user&quot;));
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.password&quot;));
You are using setJdbcUrl for everything
It should be something like
//set database connection props
securityDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.url&quot;));
securityDataSource.setUser(env.getProperty(&quot;jdbc.user&quot;));
securityDataSource.setPassword(env.getProperty(&quot;jdbc.password&quot;));
</details>

huangapple
  • 本文由 发表于 2020年9月28日 20:30:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64102236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定