1.问题描述
JAVAWEB程序中,使用String输出中文,浏览器产生了乱码格式:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "中华人民共和国";
PrintWriter out = response.getWriter();
out.println(data);
}
浏览器输出:
2.解决方法
设置请求和响应的字符编码格式为utf-8即可:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//加入了如下行
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String data = "中华人民共和国";
PrintWriter out = response.getWriter();
out.println(data);
}
上述方法行不通?
换这个试试:
response.setContentType("text/html;charset=utf-8");
可以看到浏览器已经可以正常输出中文编码了!