在servlet用getOutputStream輸出中文問題

在servlet用getOutputStream輸出中文問題

//在servlet用getOutputStream輸出中文問題
public class ResponseDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response)
            throws ServletException, IOException {
        test2(response);
    }

    private void test2(HttpServletResponse response) throws IOException,
            UnsupportedEncodingException {
        String data="中國2 ";
        //html: <meta>標籤也可以模擬一個http響應頭
        OutputStream out=response.getOutputStream();
        //out.write(data.getBytes());
        out.write("<meta http-equiv='content-type'content='text/html;charset=UTF-8'>".getBytes());
        out.write(data.getBytes("UTF-8"));
    }



    private void test1(HttpServletResponse response) throws IOException,
    UnsupportedEncodingException {
        String data="中國 ";
        //程序以什麼碼錶輸出,一定要控制瀏覽器以什麼碼錶打開
        response.setHeader("Content-type", "text/html;charset=UTF-8");——控制瀏覽器用UTF-8來打開
        OutputStream out=response.getOutputStream();
        //out.write(data.getBytes());
        out.write(data.getBytes("UTF-8"));——用UTF-8輸出數據
    }

下面寫錯了,瀏覽器會提示下載
private void test1(HttpServletResponse response) throws IOException,
    UnsupportedEncodingException {
        String data="中國 ";
        //程序以什麼碼錶輸出,一定要控制瀏覽器以什麼碼錶打開
        response.setHeader("Content-type", "text/html,charset=UTF-8");——控制瀏覽器用UTF-8來打開
        OutputStream out=response.getOutputStream();
        //out.write(data.getBytes());
        out.write(data.getBytes("UTF-8"));——用UTF-8輸出數據
    }


}
要是輸出數字5,一定要變成字符串,否則瀏覽器直接查表找5對應的字符去了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章