Servlet uses a javax.servlet.http.HttpServletResponse object to return data to the client request. How do you use it to return the following types of data? a. Text data b. Binary data
Asked
Active
Viewed 3,256 times
1
-
Can you please post the code of what you have tried? Have you looked at the documentation online? – xlm May 11 '14 at 15:17
1 Answers
1
Change the content type of the response and the content itself of the response.
For text data:
response.setContentType("text/plain");
response.getWriter().write("Hello world plain text response.");
response.getWriter().close();
For binary data ,usually for file downloading (code adapted from here):
response.setContentType("application/octet-stream");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
//file is a File object or a String containing the name of the file to download
input = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
//read the data from the file in chunks
byte[] buffer = new byte[1024 * 4];
for (int length = 0; (length = input.read(buffer)) > 0;) {
//copy the data from the file to the response in chunks
output.write(buffer, 0, length);
}
} finally {
//close resources
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}

Community
- 1
- 1

Luiggi Mendoza
- 85,076
- 16
- 154
- 332