如何设置编码方式从而在浏览器端正确显示中文
下面是测试的servlet小程序
public class TestDemo extends HttpServlet
{
ServletConfig config;
public void init(ServletConfig config)throws ServletException{
this.config = config;
System.out.println("你好");//此处在tomcat中显示的也是乱码
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException{
resp.setCharacterEncoding("UTF-8");//此处setCharacterEncoding的意思是否就是将resp响应的内容以utf-8的编码方式传输
resp.setContentType("text/html;charset=UTF-8");//此处setContentType的意思是否是在浏览器端以utf-8的方式显示
PrintWriter out = resp.getWriter();
String data = "你好";
out.print(data);
}
}
服务器用的是tomcat,正确设置了web.xml。(不知道这和tomcat有没有关系)
以上设置之后浏览器显示的是乱码,请问错在哪里了呢?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Tomcat的原因,我之前遇到这个问题,搜了一下说是tomcat编码的问题,需要更改tomcat的一个配置文件,我没改。把传递方式从post改成get就好了,
或者加下面也可以解决这个问题
你的
servlet文件编码以及页面文件编码是不是utf-8乱码问题,依次检查以下几个
容器(tomcat)、页面、数据库、过滤器、编码编译
所以你检查下tomcat、编码编译
get中的中的中文需要手动装码解码
补充一下上面的回答:除了servlet输出设置编码、tomcat设置编码以外,还要注意jsp的编码,jsp的
<head></head>标签中要有这么一个声明:<meta charset="UTF-8">;最后还要看下你的浏览器编码,以谷歌浏览器为例,点击右上角的按钮---更多工具---编码---UTF-8 要选中