I'm trying to read a file in servlet and send(Response) it to jsp as chunked message, where I can see it in browser as plain text.
Here's what I have tried:
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setHeader("Transfer-Encoding", "chunked");
response.setHeader("Connection", "keep-alive");
//response.flushBuffer();
try (PrintWriter writer = response.getWriter();BufferedReader br = new BufferedReader(new FileReader("/some/file/path.txt"))) {
String line;
while ((line = br.readLine()) != null) {
writer.println(line);
try{Thread.sleep(500);}
catch(InterruptedException e){}
}
}
}
jsp:
<head>
<meta charset="UTF-8">
<title>example</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$.get('/project/trial', function(responseText) {
$('#message').text(responseText);
});
});
</script>
</head>
<body>
<div id="message"></div>
</body>
I need to update page with new line every 500ms without refreshing page but instead I'm getting whole file at a time after whole file is read.
Am I doing something wrong? Am I missing something?
Is my jsp correct?
I tried many resources online but couldn't find out what I'm missing.
Is there any example where I can get support on chunked response reading and writing?
Thanks in advance.