我正在尝试编写一个简单的JSF应用程序,让用户在Web浏览器上登录,然后我的应用程序应验证MySQL数据库上的用户凭据。
我无法获取代码以查看database.properties文件。我对所有独立数据库程序使用以下代码,但我必须对我正在编写的这个JSF应用程序进行一些修改。
大约3/4的下一行会引发ClassNotFoundException,因为我的url变量为null,我不知道原因: FileInputStream in = new FileInputStream(url.getFile()); //如果在服务器上执行此操作
任何人都可以帮助我吗?谢谢!有问题的代码位于方法init(String fileName)的前半部分。
以下是获取数据源的整个类:
package com.gmail.gmjord.datasource;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* A simple data source for getting database connections.
*/
public class SimpleDataSource {
private static String urlString;
private static String username;
private static String password;
/**
* Initializes the data source.
*
* @param fileName
* the name of the property file that contains the database
* driver, URL, username, and password
*/
public static void init(String fileName) throws IOException,
ClassNotFoundException {
// ****************** Added code for getting resource on a server
// *********************
System.out.println("In SimpleDataSource.init()");
**Class cls = Class.forName("com.gmail.gmjord.datasource.SimpleDataSource");**
System.out.println("Made it here 1");
// returns the ClassLoader object associated with this Class
ClassLoader cLoader = cls.getClassLoader();
System.out.println("Made it here 2");
System.out.println(cLoader.getClass());
// finds resource with the given name
URL url = cLoader.getResource(fileName); // This is the original line I copied from the web page
//URL url = cls.getClass().getClassLoader().getResource(fileName); // This is TA's way
System.out.println("Made it here 3");
System.out.println("File: " + fileName);
System.out.println("url Value = " + url);
// ********* End of code for getting resource on a server*******************************************************
Properties props = new Properties();
//System.out.println("File: " + fileName);
//FileInputStream in = new FileInputStream(fileName); // Do this if not on server
FileInputStream in = new FileInputStream(url.getFile()); // Do this if on Server
props.load(in);
String driver = props.getProperty("jdbc.driver");
urlString = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
if (username == null)
username = "";
password = props.getProperty("jdbc.password");
if (password == null)
password = "";
if (driver != null)
Class.forName(driver);
}
/**
* Gets a connection to the database.
*
* @return the database connection
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(urlString, username, password);
}
}
答案 0 :(得分:1)
首先你需要将文件内部移动到src文件夹,对于下一个必须在src文件夹根目录下的代码,你可以用这种方式加载文件:
Properties properties = new Properties();
properties.load(SimpleDataSource.class.getResourceAsStream("/database.properties"));