我正在尝试编写一个简单的 JSF 应用程序来让用户在 Web 浏览器上登录,然后我的应用程序应该在 MySQL 数据库上验证用户凭据。
我无法让我的代码查看 database.properties 文件。我将以下代码用于我所有的独立数据库程序,但我必须对我正在编写的这个 JSF 应用程序进行一些修改。
下一行大约有 3/4 会抛出 ClassNotFoundException,因为我的 url 变量为空,我不知道为什么: 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);
}
}
最佳答案
首先需要将里面的文件移动到src文件夹下,接下来的代码必须在src文件夹的根目录下,可以这样加载文件:
Properties properties = new Properties();
properties.load(SimpleDataSource.class.getResourceAsStream("/database.properties"));
关于java - 如何在 JSF 项目中获取文件资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414768/