2014-05-11 34 views
0

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

+0

能否请您发布的你已经尝试了代码?你有没有在线查看文档? – xlm

回答

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