Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从Servlet获取XML文件_Java_Xml_Servlets_Fetch - Fatal编程技术网

Java 如何从Servlet获取XML文件

Java 如何从Servlet获取XML文件,java,xml,servlets,fetch,Java,Xml,Servlets,Fetch,我正在尝试从Java和Servlet获取一个XML文件。我看了很多教程,但我看过的都不管用 在my index.html中,a编写了下一个函数 document.addEventListener("DOMContentLoaded", function(){ fetch("AppServlet") .then(response => console.log(response)); });

我正在尝试从Java和Servlet获取一个XML文件。我看了很多教程,但我看过的都不管用

在my index.html中,a编写了下一个函数

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中,如果要响应get请求,必须覆盖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();
  }