这篇文章主要为大家展示了Java Servlet输出中文乱码怎么办,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
1.现象:字节流向浏览器输出中文,可能会乱码(IE低版本)
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
String date = "你好";
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(date.getBytes();
}
原因:服务器端和浏览器端的编码格式不一致。
解决方法:服务器端和浏览器端的编码格式保持一致
private void byteMethod(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 void byteMethod(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) throws IOException {
String date = "你好";
PrintWriter writer = response.getWriter();
writer.write(date);
}
原因:表示采用ISO-8859-1编码形式,该编码不支持中文
解决办法:同样使浏览器和服务器编码保持一致
private void charMethod(HttpServletResponse response) throws IOException {
// 处理服务器编码
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) throws IOException {
response.setContentType("text/html;charset=GB18030");
String date = "中国";
PrintWriter writer = response.getWriter();
writer.write(date);
}
以上就是关于Java Servlet输出中文乱码怎么办的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。