java servlet响应返回数据

时间:2014-05-11 14:59:49

标签: java servlets

Servlet使用javax.servlet.http.HttpServletResponse对象将数据返回给客户端请求。你如何使用它来返回以下类型的数据?一个。文字数据b。二进制数据

1 个答案:

答案 0 :(得分:0)

更改响应的内容类型和响应的内容本身。

对于文本数据:

response.setContentType("text/plain");
response.getWriter().write("Hello world plain text response.");
response.getWriter().close();

对于二进制数据,通常用于文件下载(代码改编自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) {}
}