很多初学者在学习web时,很容易出现中文编码问题,又不知道怎么解决,在此,我告诉大家几个关键点注意一下,即可解决。 总体上讲,只要显示的文字是对应的编码即可,如果信息为UTF-8,你非要显示ISO-8859-1,文字是中文,肯定有问题。
注意的几个部分:
Web服务器编码:
在C:\Tomcat 7.0\conf目录下找到server.xml看是什么编码
<?xml version='1.0' encoding='utf-8'?>
eclipse内文件编码:
在代码中指定显示编码:这段代码表示,内容显示是按UFT-8显示,所以可以显示中文。如果改成ISO-8859-1,则显示的中文为乱码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("你好");
out.close();
}
这是jsp代码中的编码utf-8,表示该页面显示支持中文,如果改成ISO-8859-1,则页面显示的中文就是乱码,但是从服务servlet返回的信息可以显示中文
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
如果是这样,页面显示和servlet返回的数据都是乱码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=ISO-8859-1");
PrintWriter out = response.getWriter();
out.print("你好");
out.close();
}
显示结果:??
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>