使用ServletContext接口和ClassLoader类中的方法访问资源文件

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.net.URL;
import java.util.Properties;
import javax.servlet.http.HttpServlet;

public class ResourceServlet extends HttpServlet
{
 public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
 {
  response.setContentType("text/html;charset=GB2312");
  PrintWriter pwout=response.getWriter();
  URL urlIt=getServletContext().getResource("/WEB-INF/classes/longin.properties");
  pwout.println(urlIt.toString());
  pwout.println("<br>");
  /*下面的两条语句可以实现两样的功能,但被注释的部分我没有实现,哪位好心人能帮我实现就好了,谢谢。
  it315.properties这个文件我放在了WEB-INF\classes目录中。*/ 
  //InputStream ips=getServletContext().getResourceAsStream("longin.properties");
  InputStream ips=getClass().getResourceAsStream("longin.properties");
  Properties props = new Properties();
  try
  {
   props.load(ips);
   pwout.println("database=" + props.getProperty("database"));
   pwout.println("username=" + props.getProperty("username"));
   pwout.println("password=" + props.getProperty("password"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }

  ips.close();
 }
}

注:getClass().getResourceAsStream方法只能加载位于classloader搜索目录中的资源文件,如果将longin.properties文件放在WEB-INF目录外的其它目录,就只能使用getServletContext().getResourceAsStream方法。

posted on 2007-05-07 13:53 大头剑客 阅读(688) 评论(0)  编辑  收藏 所属分类: 学习笔记


只有注册用户登录后才能发表评论。


网站导航:
 
<2025年2月>
2627282930311
2345678
9101112131415
16171819202122
2324252627281
2345678

导航

统计

公告

写字楼里写字间,写字间里程序员;
程序人员写程序,又拿程序换酒钱;
酒醒只在网上坐,酒醉还来网下眠;
酒醉酒醒日复日,网上网下年复年;
但愿老死电脑间,不愿鞠躬老板前;
奔驰宝马贵者趣,公交自行程序员;
别人笑我忒疯癫,我笑自己命太贱;
不见满街漂亮妹,哪个归得程序员.
不管前面是地雷阵还是万丈深渊,
我都将勇往直前,义无反顾,
鞠躬尽瘁,死而后已。
—— 朱镕基总理

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

学习园地

最新随笔

搜索

积分与排名

最新评论