user3625776
user3625776

Reputation: 11

java servlet response returning data

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

Upvotes: 1

Views: 3517

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85781

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) {}
}

Upvotes: 1

Related Questions