• 读取web外的配置文件


    一般web项目配置文件都放在classPath下面,读取的时候:

    1  import java.io.InputStream;
     2 import java.util.Properties;
     3    public class DealConnection {  
     4           private static String url = "";
     5           private static String user = "";
     6           private static String pwd = "";
     7           private static String connStr="";
     8  //构造方法
     9       public DealConnection() {
    10           InputStream istr = DealConnection.class.getClassLoader().getResourceAsStream("/parse.properties");//获取classPath下面的配置文件
    11           Properties p=new Properties();
    12             p.load(istr);
    13             istr.close();
    14            //获取各个配置的值
    15             url=p.getProperty("url").trim();
    16             user=p.getProperty("user").trim();
    17             pwd=p.getProperty("pwd").trim();
    18             connStr=p.getProperty("connStr");
    19    }
    20 //数据库连接方法
    21     public Connection openConn(){
    22         Connection conn=null;
    23         try {
    24             Class.forName(connStr).newInstance();
    25             conn = DriverManager.getConnection(url, user, pwd);
    26         } catch (Exception e) {
    27             e.printStackTrace();
    28         }
    29         return conn;
    30     } 
    31 }

    现在如果想把配置文件放到外面,让别人也可以方便修改配置文件,假设:配置文件放到tomcat/bin/conf文件下,就修改读取文件那里

    public DealConnection() {
            String name=System.getProperty("user.dir");//得到的路径在tomcat/bin路径
            InputStream istr;
            try {
            istr = new FileInputStream(name + "/conf/parse.properties");//读取就是tomcat/bin/conf下的配置文件
            Properties p=new Properties();
                p.load(istr);
                istr.close();
                url=p.getProperty("url").trim();
                user=p.getProperty("user").trim();
                pwd=p.getProperty("pwd").trim();
                connStr=p.getProperty("connStr");
            } catch (Exception e) {
                e.printStackTrace();
            }

    applicationContext.xml,在读取classPath配置文件的时候,路径classpath:jdbc.properties

    <!-- 属性文件的位置 -->
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <value>classpath:jdbc.properties</value>
            </property>
        </bean>

     如果要读取tomcat/bin/conf下的配置文件,路径改成:file:conf/jdbc.properties,它是相对于web容器的

    <!-- 属性文件的位置 -->
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <value>file:conf/jdbc.properties</value>
            </property>
        </bean>
  • 相关阅读:
    JQuery DOM操作
    JQuery 选择器和事件
    LinQ 组合查分页
    LinQ
    web 图片验证码 验证
    Web 上传图片加水印
    Web 组合查询加 分页
    ajax连接数据库加载+三级联动
    jq动画
    jq基础
  • 原文地址:https://www.cnblogs.com/junrong624/p/4914050.html
Copyright © 2020-2023  润新知