JSP中怎么读取配置文件

在JSP中读取配置文件分两种情况,第一种是从在servlet中读,第二种是在普通类(比如dao中读取数据库配置)中读。

第一种情况的读取方法:

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //先得到一个java.util.Properties
  //Properties p=method1();//第一种方法
  Properties p=method2();//第二种方法,可以得到文件名
  //从p中取出数据
   //方法一
  Enumeration e=p.propertyNames();
  while(e.hasMoreElements()){
   String key=(String) e.nextElement();
   response.getWriter().print(key+":"+p.getProperty(key)+"<br/>");
  }
  response.getWriter().write("------------------------<br/>");
   //方法二
  Set<Entry<Object, Object>> s=p.entrySet();
  for(Entry en:s){
   response.getWriter().write(en.getKey()+":"+en.getValue()+"<br/>");
  }
 }
 //第一种方法
 public Properties method1() throws IOException {
  /**
   *  1.通过ServletContext对象得到一个文件的流,注意文件路径的写法,这里是直接话应该程序的WEB-INF目录下的,
   *  如果是放在项目的src下,则这里的路径应该是:/WEB-INF/classes/db.properties,不过一般不会这么放
   */
  InputStream instm=this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
  //2.创建一个java.util.Properties类(此类实现了map接口),从instm输入流中读取文件的属性列表(键值对形式)
  Properties p=new Properties();
  p.load(instm);
  return p;
 }
 
 //第二种方法,可以得到文件名
 public Properties method2() throws IOException{
  String path=this.getServletContext().getRealPath("/WEB-INF/db.properties");
  FileInputStream fis=new FileInputStream(path);
  Properties p=new Properties();
  p.load(fis);
  return p;
 }

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

第二种情况的读取方法:

 public class UserDao {
 //在普通类下读取配置文件
 public void readCfg(){
  //1,通过类装载器得到这个文件的url
  /**
   * 注意:a.这里如果用.getResourceAsStream()直接得到一个流的话,那么在改动文件时,只有重新发布,
   *       才能得到最新的数据,因为这个流是能过类装载器得到的,而类只有在发布时只装载一次的,
   *       这也是为什么当类改动时,只有重新发布后,才有效果的原因,
   *      b.并且读取的文件不能太大,
   *      c.这里要写相对路径,
   */
  URL url=UserDao.class.getClassLoader().getResource("../db.properties");//注意
  //2.通过url得到文件的路径
  String path=url.getPath();
  try {
   //3,得到一个输入流
   FileInputStream fis=new FileInputStream(path);
   //InputStream fis=this.getClass().getClassLoader().getResourceAsStream("../db.properties");//这种不行
   //4.从输入流中读取文件的属性列表
   Properties p=new Properties();
   p.load(fis);
   //5.输出,使用数据
   System.out.println(p.getProperty("url"));
   
  } catch (FileNotFoundException e) {
   throw new ExceptionInInitializerError();//如果这个异常是致命的(比如数据库连不了),可以抛出这个错误
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

转载于:https://www.cnblogs.com/alern/archive/2012/09/21/2696661.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值