Java中Class.forName()在代码上无法执行报错NotFound的解决过程
更新时间:2026年06月01日 11:52:40 作者:苏木零榆
这段文章主要讨论了ClassNotFoundException的错误原因,指出问题源于文件夹命名错误,应命名为WEB-INF而非WEB-INFO,并强调了正确配置的重要性
异常信息
ClassNotFoundException
前因
在写JDBCUtils工具类的时候,发现测试时无法获取到正常的数据,查看日志后发现报错ClassNotFoundException。
错误原因
- jar包导入正常
- 所有配置文件的配置信息正常
- SQL语句以及其他代码编写正常
文件夹命名异常:
- 在web目录下的创建的目录名称必须创建为WEB-INF,但是我创建的是WEB-INFO,随后创建的lib目录,放进了jar包,因此出现了该错误。
- 然而在最初的学习中也是创建的WEB-INFO目录,却可以运行正常,目前原因未知。
代码实现
配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/userlogin username=root password=guoyuhang initialSize=5 maxActive=10 maxWait=3000
JDBC代码实现
package cn.itcast.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String password;
private static String user;
private static String driverClassName;
static {
try {
//开始读数据
Properties properties = new Properties();
//获取到该类所在的目录
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resource = classLoader.getResource("druid.properties");
String path = resource.getPath();
properties.load(new FileReader(path));
//获取数据,赋值
url = properties.getProperty("url");
user = properties.getProperty("username");
password = properties.getProperty("password");
driverClassName = properties.getProperty("driverClassName");
Class.forName(driverClassName);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源的方法 这里实现了重载 双参数和三参数
*/
public static void close(Statement stmt, Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
springBoot中myBatisPlus的使用步骤及示例代码
MyBatis-Plus 是一个 MyBatis 的增强工具,在 Spring Boot 项目里使用它能极大提升开发效率,下面为你详细介绍在 Spring Boot 中使用 MyBatis-Plus 的步骤以及示例代码,感兴趣的朋友一起看看吧2025-03-03
Apache Commons Math3探索之快速傅立叶变换代码示例
这篇文章主要介绍了Apache Commons Math3探索之快速傅立叶变换代码示例,具有一定参考价值,需要的朋友可以了解下。2017-10-10
Springboot详解整合SpringSecurity实现全过程
Spring Security基于Spring开发,项目中如果使用Springboot作为基础,配合Spring Security做权限更加方便,而Shiro需要和Spring进行整合开发。因此作为spring全家桶中的Spring Security在java领域很常用2022-07-07


最新评论