1. 程式人生 > >ServletContext讀取web中的資原始檔

ServletContext讀取web中的資原始檔

     servletcontext類字面上的意思是servlet是上下文,但是實際上就是在一個web專案裡面就只有一個servlet,所獲取到的這個類的物件都是隻有一個的;

     他的方法特別多,今天只介紹如何獲取資原始檔;

      1.原來老的方法有下面的用properties類來做:
       //1.建立屬性
        Properties properties = new Properties();
        
        //2.指定載入的資料來源
        InputStream is = new FileInputStream("src/config.properties");
        properties.load(is);
        
        //3.獲取name屬性的值
        String name = properties.getProperty("name");
        System.out.println("name="+name);

     2. 但是可以用下面的方法會更好ServletContext介面的getRealPath(Stringpath)方法返回的是資原始檔在伺服器檔案系統上的真實路徑(帶有碟符)。

引數path代表資原始檔的虛擬路徑,它應該以正斜線(/)開始,“/“表示當前web應用的根目錄,也可以不以“/“開始。

示例如下:

public class PathServlet extends HttpServlet{

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

           throwsServletException, IOException {

//”/”表示web應用的根路徑

        ServletContextservletContext=this.getServletContext();

        String path=servletContext.getRealPath("/");

       System.out.println(path);

       String indexPath=servletContext.getRealPath("/index.jsp");

       System.out.println(indexPath);

    }

}

3.也可以用set集合獲取一大批的資原始檔:

ServletContext servletcontext = this.getServletContext();
        Set<String> paths = (Set<String>) servletcontext.getResourceAsStream("/WEB-INF");
        System.out.println(paths);