servlet转发后中文乱码问题

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.

只是说如果getWriter调用过之后或者response提交之后, setCharacterEncoding是不起作用的。。。。。。也没说啥原因




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值