在servlet用getOutputStream输出中文问题

本文探讨了在使用servlet的getOutputStream方法输出中文时遇到的乱码问题,提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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对应的字符去了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值