如何设置编码方式从而在浏览器端正确显示中文
下面是测试的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有没有关系)
以上设置之后浏览器显示的是乱码,请问错在哪里了呢?
tomcat的中文编码的问题。
更改一下tomcat的配置文件就可以了。一般web开发涉及到中文都会修改这一步。
进入tomcat的安装目录,有一个conf文件夹,就是存放一些配置文件。找到里面的Server.xml文件。
找到<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/>
在后面添加utf8编码
变成这样
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
就可以的。
记得在eclipse里delete之前的tomcat,重新配置一下tomcat就可以了!