JSP的page指令中有两个有关JSP编码的属性:contentType和pageEncoding。
pageEncoding:用于指定JSP文件本身的编码,默认值为ISO-8859-1。
contentType:用于指定JSP页面的MIME类型和响应的字符集。MIME的默认类型为text/html,字符集默认为ISO-8859-1。
AppServer对JSP的编译过程(以Tomcat为例):
1.Tomcat先将整个JSP页面的代码读取出来,写到一个新的JAVA文件中。在读取JSP文件时,tomcat会先去读取JSP文件的pageEncoding属性,然后按照pageEncoding指定的编码来读取JSP文件。如果pageEncoding没有指定,tomcat会使用contentType指定的字符集编码,如果contentType也没有指定,就使用默认的ISO-8859-1编码。
2.Tomcat读取完JSP文件后,会用UTF-8编码将这些内容写道一个新的文件中,然后编译。
3.当JSP文件显示的时候,会使用contentType中指定的MIME类型和charset。如果charset没有指定,就使用pageEncoding中指定的编码,如果pageEncoding也没有指定,就使用默认的ISO-8859-1编码。
示例:
test.jsp(文件编码为UTF-8):
<html>
<head>
</head>
<body>
中国
</body>
</html>
Tomcat读取后生成的Java文件(test_jsp.java):
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<html>\r\n\t");
out.write("<head>\r\n\t");
out.write("</head>\r\n\t");
out.write("<body>\r\n\t\t??\r\n\t");
out.write("</body>\r\n");
out.write("</html>\r\n");
这说明在读取JSP文件时已经产生了乱码。
在test.jsp中加入:
< %@page pageEncoding="utf-8" % >
得到的test_jsp.java为:
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=utf-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<html>\r\n\t");
out.write("<head>\r\n\t");
out.write("</head>\r\n\t");
out.write("<body>\r\n\t\t中国\r\n\t");
out.write("</body>\r\n");
out.write("</html>\r\n");
这是Tomcat已经可以正确读取JSP文件了。