response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("欢迎用户:" + request.getAttribute("user"));
out.println("<br><br><a href=\"index.jsp\">点击退出</a>");
今天练习servlet出现一个怪问题:
以上代码是forward转发过来后用于向客户端输出一些文字。
代码中第一行就设置了charset=“utf-8”
然并卵,输出依旧是乱码,如下:
?????gx
????
找到转发之前,看看发生了什么
response.getWriter().append("Test"); //在设置字符集之前调用了getWriter(),导致转发后的页面无法设置charset
request.getRequestDispatcher(forwardPath).forward(request, response);
forward之前response已经获取过一次Writer,去掉之后,正常输出:
欢迎用户:gx
点击退出
奇了怪了,看看setCharacterEncoding是个什么鬼:
setCharacterEncoding
public void setCharacterEncoding(java.lang.String charset)
-
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
-
......
This method can be called repeatedly to change the character encoding. This method has no effect if it is called after
getWriter
has been called or after the response has been committed.Containers must communicate the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the character encoding is communicated as part of the
Content-Type
header for text media types. Note that the character encoding cannot be communicated via HTTP headers if the servlet does not specify a content type; however, it is still used to encode text written via the servlet response's writer.