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

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

          導航

          統計

          公告

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

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          學習園地

          最新隨筆

          搜索

          積分與排名

          最新評論

          主站蜘蛛池模板: 兴化市| 榆社县| 诸城市| 宝应县| 白银市| 黄冈市| 贞丰县| 保定市| 敖汉旗| 舒城县| 洪江市| 广宁县| 惠来县| 宁都县| 罗源县| 嘉定区| 岐山县| 岳阳县| 怀仁县| 买车| 仙桃市| 孙吴县| 丹棱县| 开化县| 香格里拉县| 晴隆县| 盘山县| 博白县| 莎车县| 进贤县| 宁明县| 皮山县| 宝清县| 万安县| 鄢陵县| 新安县| 犍为县| 宜州市| 佛冈县| 平潭县| 清水河县|