2011-12-25 127 views
0

我正在使用NetBeans,並且我將創建一個基於Web的應用程序,該應用程序可根據某些工具處理任何xml和json文件。到現在爲止,我已經使用html創建了一個基本站點,並且我還有一些用javabeans編寫的java代碼。 我想問你,你認爲通過java servlets讀取和處理xml或json文件的最佳方式是什麼?我怎樣才能將文件(用戶選擇的文件傳遞給可以完成進一步處理的一方)。我讀過HTTPClient類是一個好方法,但我不確定這是否是最好的。如何使用java servlets讀取json或xml文件?

感謝您的時間

回答

0

您可以使用Apache Commons FileUpload庫來處理多部分請求。多部分請求是您將包含文件元素的表單發佈到servlet時收到的。

例如:

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

import org.apache.commons.fileupload.*; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.io.FilenameUtils; 
import org.apache.commons.lang.StringUtils; 
import org.apache.log4j.Logger; 

(...) 

    public void doPost(HttpServletRequest request, HttpServletResponse response) { 
     if (ServletFileUpload.isMultipartContent(request)) { 
      handleMultiPartContent(request); 
     } 
    } 

    private void handleMultiPartContent(HttpServletRequest request) { 

     ServletFileUpload upload = new ServletFileUpload(); 
     upload.setFileSizeMax(2097152); // 2 Mb 
     try { 
      FileItemIterator iter = upload.getItemIterator(request); 
      while (iter.hasNext()) { 
       FileItemStream item = iter.next(); 
       if (!item.isFormField()) { 
        File tempFile = saveFile(item); 
        // process the file 
       } 
      } 
     } 
     catch (FileUploadException e) { 
      LOG.debug("Error uploading file", e); 
     } 
     catch (IOException e) { 
      LOG.debug("Error uploading file", e); 
     } 
    } 

    private File saveFile(FileItemStream item) { 

     InputStream in = null; 
     OutputStream out = null; 
     try { 
      in = item.openStream(); 
      File tmpFile = File.createTempFile("tmp_upload", null); 
      tmpFile.deleteOnExit(); 
      out = new FileOutputStream(tmpFile); 
      long bytes = 0; 
      byte[] buf = new byte[1024]; 
      int len; 
      while ((len = in.read(buf)) > 0) { 
       out.write(buf, 0, len); 
       bytes += len; 
      } 
      LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath())); 
      return tmpFile; 
     } 
     catch (IOException e) { 

      LOG.debug("Could not save file", e); 
      Throwable cause = e.getCause(); 
      if (cause instanceof FileSizeLimitExceededException) { 
       LOG.debug("File too large", e); 
      } 
      else { 
       LOG.debug("Technical error", e); 
      } 
      return null; 
     } 
     finally { 
      try { 
       if (in != null) { 
        in.close(); 
       } 
       if (out != null) { 
        out.close(); 
       } 
      } 
      catch (IOException e) { 
       LOG.debug("Could not close stream", e); 
      } 
     } 
    } 

這上傳文件並將其保存爲在服務器的硬盤的臨時文件。然後您可以使用該文件所需的東西。

特別是對於非常大的文件,更好的方法可能是跳過保存並直接處理InputStream。你需要一個合適的XML庫(例如Stax),它可以直接處理流。

編輯:你的表單的動作屬性應該匹配你的servlet映射的url-pattern。

示例HTML:

<form action="upload" ENCTYPE='multipart/form-data' method="POST"> 
    <input type="file" name="user_file" accept="text/xml"> 
    <input type="submit" value="Validate" /> 
</form> 

例的web.xml片段:

<servlet> 
    <servlet-name>FileReaderServlet</servlet-name> 
    <servlet-class>my.application.FileReaderServlet</servlet-class> 
</servlet> 

<servlet-mapping> 
    <servlet-name>FileReaderServlet</servlet-name> 
    <url-pattern>/upload</url-pattern> 
</servlet-mapping> 
+0

謝謝!我將這段代碼用於我的servlet,但它實際上什麼都不做。我對這個領域很陌生,我猜想我所做的事情缺少一些東西。在JSP文件中,我獲得了html代碼。與servlet通信的表單如下:

當我讀到時,當我在'action'部分使用servlet名稱,那麼JSP文件就與這個servlet連接,並執行Post方法! – Angelina 2011-12-27 12:10:38

+0

我真的不知道問題在哪裏。就像驗證按鈕對它沒有任何操作一樣,它什麼都不做。至少沒有什麼是顯而易見的。再次感謝! – Angelina 2011-12-27 12:13:35

+0

你有沒有在web.xml中定義和映射你的servlet? – 2011-12-28 08:00:39

0

您可以使用由阿帕奇(或)Sun提供HttpURLClient提供HttpClient的,都是不錯的API。如果你選擇Apache,你需要安裝額外的罐子。

Apache HttpClient有一些額外的方法與Sun提供的方法相比。

+0

好的,謝謝,我會嘗試一個提供bt apache的。我發現需要一些罐子,我安裝它們,現在試圖把它們放在一起。 – Angelina 2011-12-27 12:04:27