簡體   English   中英

如何從Servlet提取XML文件

[英]How to fetch and XML file from Servlet

我正在嘗試從Java Servlet中獲取XML文件。 我看了很多教程,但我看過的都沒有。

在我的index.html中寫了下一個函數

document.addEventListener("DOMContentLoaded", function(){
                fetch("AppServlet")
                        .then(response => console.log(response));
            });

而該獲取的響應是...

Response {type: "basic", url: "http://localhost:8080/TW/AppServlet", redirected: false, status: 200, ok: true, …}
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "http://localhost:8080/TW/AppServlet"
__proto__: Response

但是問題出在我的AppServlet上。 我不知道如何發送位於我的WEB PAGES目錄中的一個XML文件。 有沒有簡單的方法可以實現?

如果要響應獲取請求,則必須在servlet中覆蓋doGet()方法。

對於發送xml文件,我認為應該是這樣的。

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    File xmlFile = new File("someFile.xml"); //Your file location
    long length = xmlFile.length();

    resp.setContentType("application/xml");
    resp.setContentLength((int) length);

    byte[] buffer = new byte[1024];
    ServletOutputStream out = resp.getOutputStream();

    try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(xmlFile))) {
      int bytesRead = 0;
      while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
      }
    }

    out.flush();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM