读取WEB-INF下配置文件

本文详细解析了Java中通过properties文件加载数据库配置的过程,包括使用公共类公共方法实现跨类加载数据库配置,并通过实例代码展示如何从配置文件中获取数据库连接参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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;
	}

 

转载于:https://www.cnblogs.com/king-sheng/archive/2012/12/25/2832181.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值