java - 如何从 Servlet 获取和 XML 文件
问题描述
我正在尝试从 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();
}
推荐阅读
- mongodb - MongoDB:设置和获取子文档模式
- ionic4 - Ionic 4如何在点击时更改段
- javascript - 错误说 queryResult 未定义,即使 queryResult 包含数据
- javascript - 如何防止使用plupload上传时自动重定向?
- c++ - c++ 运算符重载 - 我实际返回的是什么操作数类型?
- python - 如何在剪刀石头布程序中添加赢/输计数器
- oracle - 为预订服务报告调试 PL/SQL 过程
- zsh - Zshell 完成调用另一个函数
- c - C在没有#include的情况下告诉头文件关于ac文件中的结构
- ios - 如何安排和重复本地通知