[英]How to Read db.properties File from WEB-INF
I am using netbeans. 我正在使用netbeans。 I want to read db.properties file from WEB-INF Folder. 我想从WEB-INF文件夹中读取db.properties文件。 But it return null; 但是它返回null;
InputStream input = getClass().getClassLoader().getResourceAsStream("db.properties"); // returning null
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/db.properties"); // returning null.
But when I put my db.properties file int Web_INF/classes above code work fine. 但是,当我将db.properties文件放入Web_INF / classs上面的代码时,效果很好。
the following code throws File not found in both cases. 以下代码抛出两种情况下都找不到的文件。 (in Web-INF/db.properties and in Web-INF/classes/db.properties). (在Web-INF / db.properties和Web-INF / classes / db.properties中)。
FileInputStream fileInput = new FileInputStream(new File("db.properties")); //throws exception
Any Clue. 任何线索。
package com.towertech.db;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.tomcat.jdbc.pool.*;
public class DataSource
{
PoolProperties poolProperties;
org.apache.tomcat.jdbc.pool.DataSource datasource;
ClassLoader classLoader;
InputStream input;
FileInputStream fileInput;
Properties properties;
public org.apache.tomcat.jdbc.pool.DataSource getDatasource() {
return datasource;
}
public void setDatasource(org.apache.tomcat.jdbc.pool.DataSource datasource) {
this.datasource = datasource;
}
public DataSource() throws FileNotFoundException, IOException
{
input = getClass().getClassLoader().getResourceAsStream("/WEB-INF/db.properties");
input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/WEB-INF/db.properties");
fileInput = new FileInputStream(new File("/WEB-INF/db.properties"));
if(input == null)
properties.load(fileInput);
else
properties.load(input);
poolProperties = new PoolProperties();
poolProperties.setDbProperties(properties);
datasource.setPoolProperties(poolProperties);
}
public static void main(String[] args) throws IOException
{
DataSource ds = new DataSource();
System.out.println(ds.toString());
}
public Connection getConnection() throws SQLException
{
return datasource.getConnection();
}
public void returnConnection(Connection con) throws SQLException
{
con.close();
}
}
You can read properties file under WEB-INF
inside the Spring controller using the servletcontext
object as shown below: 您可以使用servletcontext
对象在Spring控制器内的WEB-INF
下读取属性文件,如下所示:
@Controller
public class MyController {
@RequestMapping(value="/myMapping")
public R myMethod(HttpServletRequest request, ...) {
//Get the servletcontext from request
InputStream input = request.getSession().getServletContext().
getResourceAsStream("/WEB-INF/db.properties");
//read properties
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.