WEB中通过普通java程序读取.properties资源文件

DB.properties文件数据:

url=jdbc:mysql://locahost:3306/text
username=root
password=123

servlet页面代码:

package com.properlet;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class ServletDemo extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ServletContext context = this.getServletContext();
        
        UserDao dao = new UserDao();
        try {
            dao.update(context);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

UserDao.java 静态方法代码:

package com.properlet;

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;

public class UserDao {
    
    private static Properties dbconfig = new Properties();
    //静态方法第一次连接便获取数据,之后可复用,不需要再次连接
    static{
        try{
        //通过类装载器
        InputStream in = UserDao.class.getClassLoader().getResourceAsStream("DB.properties");
        dbconfig.load(in);
        }catch(Exception e){
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public void update(ServletContext context) throws Exception{
     System.out.println(dbconfig.getProperty("url"));
}

当修改DB.properties文件时:

import java.io.FileInputStream;
import java.util.Properties;

import javax.servlet.ServletContext;

public class UserDao {
    
private static Properties dbconfig = new Properties();
public void update(ServletContext context) throws Exception{ String path = UserDao.class.getClassLoader().getResource("DB.properties").getPath(); FileInputStream in = new FileInputStream(path); dbconfig.load(in); System.out.println(dbconfig.getProperty("url")); } }

 

posted on 2013-11-17 15:04  小-小鱼  阅读(245)  评论(0)    收藏  举报

导航