HttpServletResponse中文输出乱码问题

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class _03_中文输出乱码 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String str = "中国加油,河南加油!";
        PrintWriter output = resp.getWriter();
        output.write(str);
    }

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

显示:

 response对象的字符输出流在编码时,采用的时ISO 8859-1 的字符码表,该码表并不见容中文

会将查不到的字符显示为63,也就是"?",所以输出为乱码。

HttpServletResponse接口中,提供了一个setCharacterEncoding()方法来设置编码。

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        String str = "中国加油,河南加油!";
        PrintWriter output = resp.getWriter();
        output.write(str);
    }

然火狐的样式是这样的

Chrome是这样的

 

为什么还是乱码呢?这是由于浏览器解码错误导致,程序用的是UTF-8,而浏览器用的编码不同,所以会导致乱码,修改浏览器的解码方式即可。

火狐

Chrome的话新版修改编码有点麻烦,就不演示了

 但是这样修改浏览器编码的方法不可取,因为大部分人都不会修改浏览器编码,所以

HttpServletResponse对象提供了两种方法,

1.

        //1.设置编码
        resp.setCharacterEncoding("UTF-8");
        //2.通知浏览器使用utf-8编码
        resp.setHeader("Content-Type","text/html;charset=utf-8");

 2.

        resp.setContentType("text/html;charset=utf-8");

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值