簡體   English   中英

java servlet響應返回數據

[英]java servlet response returning data

Servlet使用javax.servlet.http.HttpServletResponse對象將數據返回到客戶端請求。 您如何使用它返回以下類型的數據? 一種。 文字數據b。 二進制數據

更改響應的內容類型和響應的內容本身。

對於文本數據:

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

對於二進制數據,通常用於文件下載(代碼從此處改編):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM