在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对应的字符去了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章