[Resolved] jsp设定了charset=utf-8, 中文仍然显示为问号

8次阅读

共计 1336 个字符,预计需要花费 4 分钟才能阅读完成。

2019 年 3 月 13 日 21:53:04
今天遇到这样的问题, 有关于 Java 的 charset. 当 jsp 已设置 charset 及 pageEncoding 为 utf8 后, 对应界面出现了中文在界面上变为问号的情况. 记录一下解决办法.
背景: servlet3.1+jsp+tomcat85+eclipsePhoton 现象: jsp 设定了 charset 以及 paeEncoding 为 utf8 后, 仍然中文变成问号, 查看页面信息, page info 显示页面 text Encoding 为 windows-1252, 浏览器控制台显示 response 对象的 charset=ISO-8859-1, 所以相当于 jsp 页面的 charset 设置没有起作用. 线索: 几经辗转, 发现问题在 servlet 上, servlet 是有系统自动创建的, 每一个自动创建的 servlet 类都带有这么一行: response.getWriter().append(“Served at: “).append(request.getContextPath()); 其中的 getWriter() 方法的说明如下: Returns a PrintWriter object thatcan send character text to the client.The PrintWriter uses the characterencoding returned by getCharacterEncoding.If the response’s character encoding has not beens pecified as described in getCharacterEncoding(i.e., the method just returns the default value ISO-8859-1), getWriterupdates it to ISO-8859-1. 所以线索已经很清晰, 因为在 servlet 中调用了 response 的 getWriter 方法, 而 getWriter 方法会在 response 对象没有被设置 character encoding 的话, getWriter 会自动将其设置为 ISO-8859-1. 解决方案: 去掉这一行固然是解决办法, 但还有另外一种迎面而上的方式: 为 response 手动设置 character encoding, 在 getWriter 上一行, 加上 response.setCharacterEncoding(“UTF-8”); 或 response.setContentType(“text/html;charset=utf-8”); 即可解决

但问题虽然解决, 这只是一个问题点, 由这个点, 带来的是一个知识面的问题, 比如:

response setCharacterEncoding 和 setContentType 的区别是什么?
如果亲自试过, 会发现吧 setCharacterEncoding 插在 getWriter 和 forward 之间是不起作用的, 原因是什么?getWriter.write() 涉及到的 response 缓冲区是什么? 对应的 out 缓冲区是什么? 执行顺序如何?
此问题中, getwriter.write 和 RequestDispatcher.forward 同时存在, 为什么最后只有 forward 方法实现了?

正文完
 0