【问题标题】:How to fetch and XML file from Servlet如何从 Servlet 获取和 XML 文件
【发布时间】:2019-06-16 04:55:09
【问题描述】:

我正在尝试从 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 文件。 有没有简单的方法让它成为可能?

【问题讨论】:

    标签: java xml servlets fetch


    【解决方案1】:

    如果您想响应获取请求,则必须在您的 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();
      }
    

    【讨论】:

      猜你喜欢
      • 2013-03-15
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 2012-08-01
      • 1970-01-01
      相关资源
      最近更新 更多