1. 程式人生 > >JavaWeb學習(四)HttpServletResponse基本應用——使用OutputStream或者PrintWriter輸出數字(3)

JavaWeb學習(四)HttpServletResponse基本應用——使用OutputStream或者PrintWriter輸出數字(3)

一、程式碼:

package com.servlet.study;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseD extends HttpServlet {

    private static final long serialVersionUID = 4312868947607181532L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        outputOneByOutputStream(response);//使用OutputStream輸出1到客戶端瀏覽器
        
    }

    /**
     * 使用OutputStream流輸出數字1
     * @param request
     * @param response
     * @throws IOException 
     */
    public void outputOneByOutputStream(HttpServletResponse response) throws IOException{
        response.setHeader("content-type", "text/html;charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write("使用OutputStream流輸出數字1:".getBytes("UTF-8"));
        //outputStream.write(1);
        outputStream.write((1+"").getBytes());
    }
    
}

執行結果:

二、注意:

outputStream.write((1+"").getBytes());

1+""這一步是將數字1和一個空字串相加,這樣處理之後,數字1就變成了字串1了,然後再將字串1轉換成位元組陣列使用OutputStream進行輸出。

參考:https://www.cnblogs.com/xdp-gacl/p/3789624.html