读取WEB-INF下配置文件

 public DbDriver(){
    	//读取WEB-INF的路径
    	try{
    		/*String path=this.getClass().getResource("/").getPath()+"config.properties";
            path=path.substring(0,path.indexOf("classes")-1)+"/dbConfig.properties";*/    
    		String path=DbDriver.class.getResource("/").getPath();
    		String websiteUrl = path.replace("/build/classes","").replace("%20", " ")+"/WebContent/WEB-INF/dbConfig.properties";
            setParameter(websiteUrl);
    	}catch(Exception e){
    		e.printStackTrace();
    	}   	
    }
    
	private void setParameter(String path) throws Exception{
		properties=new Properties();
		fileInputStream=null;
		try{
			fileInputStream=new FileInputStream(path);
			properties.load(fileInputStream);
			dbDriver=properties.getProperty("database.driverClassName");
			dbUrl=properties.getProperty("database.url");
			dbPassword=properties.getProperty("database.password");
			dbUser=properties.getProperty("database.username");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			fileInputStream.close();
		}
	}

2.dbConfig.properties文件如下:

 database.driverClassName=com.mysql.jdbc.Driver
 database.url=jdbc:mysql://localhost:3306/db_reviewboard
 database.username=root
 database.password=password

3.文件结构如下:

E:\Sts Workspace\csv\build\classes\demo\ceo\csv\test\QueryData.class

E:\Sts Workspace\csv\WebContent\WEB-INF\dbConfig.properties

 

方法二:自己新建个files文件夹

public Properties getProperties(String propFileName) {
		if(props == null) {
			props = new Properties();
			try {
				String path =LoadProperties.class.getResource("/").getPath();									
				String websiteUrl = path.replace("/WEB-INF/classes","");
				String filePath = websiteUrl + "files/" + propFileName;
				log.debug("filePath: " + filePath);
				
				props.load(new FileInputStream(filePath));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
		return props;
	}

 

posted @ 2012-12-25 12:34  柠檬Cool  阅读(9047)  评论(0编辑  收藏  举报