首页 > 未分类 > [收藏]JSP的编码问题

[收藏]JSP的编码问题

2005年12月26日 发表评论 阅读评论

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文件了。

分类: 未分类 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word


Warning: fsockopen() has been disabled for security reasons in /home/onlymars/public_html/wp/wp-includes/class-snoopy.php on line 1148