Reputation: 167
I'm trying to fetch an XML file from and Java Servlet. I watch a lot of tutorials but none of the ones I've seen work.
In my index.html a wrote the next function
document.addEventListener("DOMContentLoaded", function(){
fetch("AppServlet")
.then(response => console.log(response));
});
And the response of that fetch is ...
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
But the problem is with my AppServlet. I have no idea how to send one XML file located in my WEB PAGES directory. Is there an easy way to make it possible?
Upvotes: 0
Views: 664
Reputation: 152
In your servlet you have to overwrite the doGet() method if you want to respond to get requests.
For sending an xml file I think it would be something like this.
@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();
}
Upvotes: 1