1

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

1
  • Can you please post the code of what you have tried? Have you looked at the documentation online? Commented May 11, 2014 at 15:17

1 Answer 1

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) {}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.