2012-01-24 58 views
0

我從絕對路徑中查看了BalusC的定製下載servlet的代碼(請參閱http://balusc.blogspot.com/2007/07/fileservlet.html#FileServletServingFromAbsolutePath)。我不是一個Java Web開發專家,所以我會很喜歡,如果什麼時候init方法被調用有人能explainme代碼自定義下載servlet

private String filePath; 

// Actions ------------------------------------------------------------------------------------ 

public void init() throws ServletException { 

    // Define base path somehow. You can define it as init-param of the servlet. 
    this.filePath = "/files"; 

    // In a Windows environment with the Applicationserver running on the 
    // c: volume, the above path is exactly the same as "c:\files". 
    // In UNIX, it is just straightforward "/files". 
} 

的一部分?爲什麼我們需要在init方法中設置filePath?

我有一個XHTML(Mojarra + IceFaces)類似下面的代碼,很好用。我的頁面丟失下載這是由outputLink標籤

   <ice:tree id="tree" 
          value="#{treeBean.model}" 
          var="item" 
          hideRootNode="false" 
          hideNavigation="false" 
          > 
        <ice:treeNode> 
         <f:facet name="icon"> 
          <ice:panelGroup style="display: inline"> 
           <h:graphicImage value="#{item.userObject.icon}" /> 
          </ice:panelGroup> 
         </f:facet> 
         <f:facet name="content"> 
          <ice:panelGroup style="display: inline-block"> 
           <ice:outputLink value="#{item.userObject.filePath}"> 
            <ice:outputText value="#{item.userObject.fileName}"/> 
           </ice:outputLink> 
          </ice:panelGroup> 
         </f:facet> 
        </ice:treeNode> 
       </ice:tree> 

引用我支持bean中我有兩個字段fileNamefilepath(只是在filewith擴展名,比如Image.jpeg的名稱)的文件只是部分(服務器中文件的ABSOLUTE路徑)。最後我想用自定義servelet下載文件,我該怎麼做?

乾杯,

UPDATE

假設MI基礎-dir是/SRC和目錄下,我有我所有的XHTML頁面和WEB-INF和META-INF和方法,另外我有一個目錄所謂數據文件下的數據文件,我有以下結構

--dataFiles 
    |----Enterprise1 
    | |--User1 
    | | |--goodFiles 
    | | | |--ok.txt 
    | | |--badFiles 
    | |  |--bad.txt 
    | |--User2 
    | | |--goodFiles 
    | | | |--ok.txt 
    | | |--badFiles 
    | |  |--bad.txt 
    |----Enterprise2 
     |--User1 
     | |--goodFiles 
     | | |--ok.txt 
     | |--badFiles 
     |  |--bad.txt 
     |--User2 
      |--goodFiles 
      | |--ok.txt 
      |--badFiles 
       |--bad.txt 

這就是我如何呈現樹與ICEfaces的,我只是有後臺bean中的文件名(即ok.txt或bad.txt),但我無法弄清楚如何通過樹中的鏈接下載指向的文件。

回答

0

好了,終於搞定了。

首先感謝BalusC,這裏有一些帖子幫助我理解,但有人刪除它們。無論如何,這是我所學到的。

  1. 在Servlet的初始化方法文件路徑變量必須指向絕對所在的路徑要下載的文件是。
  2. web.xml中在servlet-地圖的url-pattern會導致執行servlet當瀏覽器有一個URL模式。
  3. 在鏈接的XHTML頁面THA值應與url-pattern的依次是姓名(或路徑+文件名),所以你點擊下載開始鏈接時開始。

這就是我不得不這樣做!

在問題的例子,在servlet的init方法的文件路徑變量將指向絕對路徑,像C:\對myApp \數據文件 然後在XHTML將調用servlet的東西,如

<ice:outputLink value="dl/myPath/#{myBean.fileName}> 
    <ice:outputText value="#{myBean.fileName}"/> 
</ice:outputLink> 

注1:表示outputLink的值的第一部分是DL/這是因爲爲servlet到下載鏈接模式被映射到它

注2:在outputLink的所述的價值 mypath中可能是DL/Enterprise1 /用戶1/file1.ext

乾杯

+0

我因爲這個問題成了方式過於寬泛和本地化的,我沒有看到你真正的問題了自己刪除了。僅僅花費更多的時間來計算/猜測你的具體問題是不值得的。 – BalusC

+0

認爲你是對的。但是,無論如何,在您的建議下我解決了我的問題。 – BRabbit27