java servlet response returning data

↘锁芯ラ 提交于 2019-12-25 06:33:14

问题


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:


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


来源:https://stackoverflow.com/questions/23594132/java-servlet-response-returning-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!