相信很多同学和我一样遇到过在通过服务器响应界面界面浏览器界面出现乱码的问题吧,今天我们就来思考一下如何解决乱码问题!
乱码产生的原因:
1.Servlet程序输出给浏览器的内容,不是任何一种中文字符集编码
2.浏览器浏览网页文档是所有采用的字符集编码与它接收到的中文字符集本身的字符编码不一致。
- //response对象 因为getbytes对象获取的是gb2312的数据,而浏览器采用的默认编码是gb2312,所以就不会出现乱码
- <pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">response.getOutputStream().write("贤贤学java".getBytes());
"text/html;charset=utf-8");
<pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">/*第二种*/response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
- <pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">/*第二种*/response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
- response.getOutputStream().write("中国".getBytes("UTF-8"));
- /*OutPutStream流在浏览器上输出数字*/
- response.getOutputStream().write((98+"").getBytes());
本文探讨了乱码产生的原因,并提供了两种解决乱码问题的方法:一是通过设置`response.setHeader`来指定内容类型编码;二是使用HTML元标记`<meta>`来指定编码。此外,还展示了如何在输出流中正确处理中文字符。

2万+

被折叠的 条评论
为什么被折叠?



