java servlet 中文乱码_Java中Servlet输出中文乱码问题

1.现象:字节流向浏览器输出中文,可能会乱码(IE低版本)

private voidbyteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {

String date= "你好";

ServletOutputStream outputStream=response.getOutputStream();

outputStream.write(date.getBytes();

}

原因:服务器端和浏览器端的编码格式不一致。

解决方法:服务器端和浏览器端的编码格式保持一致

private voidbyteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {

String date= "你好";

ServletOutputStream outputStream=response.getOutputStream();//浏览器端的编码

response.setHeader("Content-Type", "text/html;charset=utf-8");//服务器端的编码

outputStream.write(date.getBytes("utf-8"));

}

或者简写如下

private voidbyteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {

String date= "你好";

ServletOutputStream outputStream=response.getOutputStream();//浏览器端的编码

response.setContentType("text/html;charset=utf-8");//服务器端的编码

outputStream.write(date.getBytes("utf-8"));

}

2.现象:字符流向浏览器输出中文出现   ???乱码

private void charMethod(HttpServletResponse response) throwsIOException {

String date= "你好";

PrintWriter writer=response.getWriter();

writer.write(date);

}

原因:表示采用ISO-8859-1编码形式,该编码不支持中文

解决办法:同样使浏览器和服务器编码保持一致

private void charMethod(HttpServletResponse response) throwsIOException {//处理服务器编码

response.setCharacterEncoding("utf-8");//处理浏览器编码

response.setHeader("Content-Type", "text/html;charset=utf-8");

String date= "中国";

PrintWriter writer=response.getWriter();

writer.write(date);

}

注意!setCharacterEncoding()方法要在写入之前使用,否则无效!!!

或者简写如下

private void charMethod(HttpServletResponse response) throwsIOException {

response.setContentType("text/html;charset=GB18030");

String date= "中国";

PrintWriter writer=response.getWriter();

writer.write(date);

}

总结:解决中文乱码问题使用方法 response.setContentType("text/html;charset=utf-8");可解决字符和字节的问题。

如有问题还望指正!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值