gpt4 book ai didi

java - 如何从 Servlet 获取 XML 文件

转载 作者:行者123 更新时间:2023-12-02 09:46:20 26 4
gpt4 key购买 nike

我正在尝试从 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 中,如果您想响应 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();
}

关于java - 如何从 Servlet 获取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56616188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com