使用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 大頭劍客 閱讀(695) 評論(0)  編輯  收藏 所屬分類: 學習筆記

          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導航

          統計

          公告

          寫字樓里寫字間,寫字間里程序員;
          程序人員寫程序,又拿程序換酒錢;
          酒醒只在網上坐,酒醉還來網下眠;
          酒醉酒醒日復日,網上網下年復年;
          但愿老死電腦間,不愿鞠躬老板前;
          奔馳寶馬貴者趣,公交自行程序員;
          別人笑我忒瘋癲,我笑自己命太賤;
          不見滿街漂亮妹,哪個歸得程序員.
          不管前面是地雷陣還是萬丈深淵,
          我都將勇往直前,義無反顧,
          鞠躬盡瘁,死而后已。
          —— 朱镕基總理

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          學習園地

          最新隨筆

          搜索

          積分與排名

          最新評論

          主站蜘蛛池模板: 黄平县| 蓬溪县| 旬邑县| 五常市| 忻州市| 夏津县| 阿克陶县| 祁门县| 四川省| 马龙县| 彝良县| 甘肃省| 汶川县| 九龙县| 遂溪县| 乐都县| 佛冈县| 马山县| 亳州市| 嫩江县| 萨嘎县| 慈利县| 甘南县| 道孚县| 德兴市| 大同县| 盐池县| 栖霞市| 翁牛特旗| 双流县| 玉环县| 营山县| 文水县| 长乐市| 崇信县| 宁晋县| 句容市| 博白县| 宜良县| 绵阳市| 织金县|