Java Servlet输出中文乱码问题解决方案
1.现象:字节流向浏览器输出中文,可能会乱码(IE低版本)
privatevoidbyteMethod(HttpServletResponseresponse)throwsIOException,UnsupportedEncodingException{
Stringdate="你好";
ServletOutputStreamoutputStream=response.getOutputStream();
outputStream.write(date.getBytes();
}
原因:服务器端和浏览器端的编码格式不一致。
解决方法:服务器端和浏览器端的编码格式保持一致
privatevoidbyteMethod(HttpServletResponseresponse)throwsIOException,UnsupportedEncodingException{
Stringdate="你好";
ServletOutputStreamoutputStream=response.getOutputStream();
//浏览器端的编码
response.setHeader("Content-Type","text/html;charset=utf-8");
//服务器端的编码
outputStream.write(date.getBytes("utf-8"));
}
或者简写如下
privatevoidbyteMethod(HttpServletResponseresponse)throwsIOException,UnsupportedEncodingException{
Stringdate="你好";
ServletOutputStreamoutputStream=response.getOutputStream();
//浏览器端的编码
response.setContentType("text/html;charset=utf-8");
//服务器端的编码
outputStream.write(date.getBytes("utf-8"));
}
2.现象:字符流向浏览器输出中文出现???乱码
privatevoidcharMethod(HttpServletResponseresponse)throwsIOException{
Stringdate="你好";
PrintWriterwriter=response.getWriter();
writer.write(date);
}
原因:表示采用ISO-8859-1编码形式,该编码不支持中文
解决办法:同样使浏览器和服务器编码保持一致
privatevoidcharMethod(HttpServletResponseresponse)throwsIOException{
//处理服务器编码
response.setCharacterEncoding("utf-8");
//处理浏览器编码
response.setHeader("Content-Type","text/html;charset=utf-8");
Stringdate="中国";
PrintWriterwriter=response.getWriter();
writer.write(date);
}
注意!setCharacterEncoding()方法要在写入之前使用,否则无效!!!
或者简写如下
privatevoidcharMethod(HttpServletResponseresponse)throwsIOException{
response.setContentType("text/html;charset=GB18030");
Stringdate="中国";
PrintWriterwriter=response.getWriter();
writer.write(date);
}
总结:解决中文乱码问题使用方法response.setContentType("text/html;charset=utf-8");可解决字符和字节的问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。