2016-11-25 60 views
0

我正在使用netbeans。我想從WEB-INF文件夾讀取db.properties文件。但它返回null;如何從WEB-INF讀取db.properties文件

InputStream input = getClass().getClassLoader().getResourceAsStream("db.properties"); // returning null 

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/db.properties"); // returning null. 

但是當我把我的db.properties文件int Web_INF/classes上面的代碼工作正常。

以下代碼在兩種情況下都會拋出File not found。 (在Web-INF/db.properties和Web-INF/classes/db.properties中)。

FileInputStream fileInput = new FileInputStream(new File("db.properties")); //throws exception 

任何線索。

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(); 
}  
} 
+0

有U使用servlet?還是Spring的控制器?任何其他 ? – developer

+0

我正在使用Spring web服務 – MUHIUDDIN

+0

這是從控制器或服務調用的?我的意思是DataSource類,從哪裏/將如何調用? – developer

回答

1

你可以閱讀,如下所示的屬性WEB-INF使用servletcontext對象春節控制器內部文件下:

@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 

    } 
}