2012-09-17 21 views
0

我在WEB-INF目錄中有一個Web應用程序和XML文件。我需要加載這個XML文件。有沒有加載它,而不是使用getServletContext().getResourceAsStream("/WEB-INF/test.xml");在WEB-INF文件夾下加載資源

我試着像Thread.currentThread().getContextClassLoader().getResourceAsStream("/WEB-INF/test.xml");

它是不工作的選擇的其他方式。

你能幫我嗎?

+0

問: 「getServletContext()」方法究竟有什麼問題? – paulsm4

+0

我想從一個靜態塊加載它。 – Don

+0

duplicate [如何從Web檔案的WEB-INF目錄加載資源](http://stackoverflow.com/questions/1108434/howto-load-a-resource-from-web-inf-directory-of-a- web-archive) – user1406062

回答

1

您可以從您的應用程序(jsp-servlet)內部僅使用/WEB-INF/test.xml訪問WEB-INF文件夾中的資源。

<!%@ taglib uri="/WEB-INF/tiles-jsp.tld" prefix="tiles" %> 

如果你想讓它對Web用戶可用,那麼它不能被直接訪問。爲了讓用戶直接訪問它,必須有某種接口將文件從WEB-INF文件夾(例如,讀取文件/WEB-INF/test.xml並將其輸出到jsp/servlet中的jsp )

UPDATE

讀取使用一個Servlet使用本文件:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    StringBuffer strContent = new StringBuffer(""); 
    int ch; 
    PrintWriter out = response.getWriter(); 
    try { 
     String path = getServletContext().getRealPath("/WEB-INF/newfile.xml"); 
     File file = new File(path); 
     FileInputStream fin = null; 
     try { 
      fin = new FileInputStream(file); 
      while ((ch = fin.read()) != -1) { 
       strContent.append((char) ch); 
      } 
      fin.close(); 
     } catch (FileNotFoundException e) { 
      System.out.println("File " + file.getAbsolutePath() 
        + " could not found"); 
     } catch (IOException ioe) { 
      System.out.println("Exception while reading the file" + ioe); 
     } 
     System.out.println("File contents :"); 
     System.out.println(strContent); 
    } finally { 
     out.close(); 
    } 
} 

這將讀取WEB-INF名爲newfile.xml一個文件,將輸出內容到控制檯。輸出將是這樣的:

文件內容:

<一>

< B> XXXX </B>

</A>

+0

我需要從我的Servlet類的靜態塊中讀取它。 – Don

+0

看到我更新的答案 – MaVRoSCy

+0

我需要從我的課程中的一個靜態塊做到這一點。我不會從那裏調用getServletContext()。 – Don