setContentType(“text/html;charset=utf8”)后页面依然乱码

写了段servlet返回浏览器中文的代码,设置了返回编码为“utf-8”,但是在浏览器端看到的仍是乱码,代码如下:

public class ServletTest extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		PrintWriter pw = res.getWriter();
		res.setContentType("text/html;charset=utf8");
		pw.write("尼美的");
		pw.close();
	}
}

后来发现,setContentType应该写在getWriter前面,所以啊,顺序还是很重要的!!!

res要先设定,才能保证通过res获得的流是utf8的格式。正确代码如下:

public class ServletTest extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html;charset=utf8");
		PrintWriter pw = res.getWriter();
		pw.write("尼美的");
		pw.close();
	}
}