当前位置: 代码迷 >> Web前端 >> page mata标签指定contenttype差别
  详细解决方案

page mata标签指定contenttype差别

热度:126   发布时间:2012-11-16 14:12:14.0
page mata标签指定contenttype区别


一.引子
下面的servlet能显示中文吗?

public class SimpleServlet extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
                     java.io.IOException{
        resp.setContentType("text/html");
        PrintWriter w = resp.getWriter();
        System.out.println("响应的输出编码器:" + resp.getCharacterEncoding());

        w.println("<html>");
        w.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        w.println("<head>");
        w.println("<title>文字与图片</title>");
        w.println("</head>");
        w.println("<body>");
        w.println("文字与图片");
        w.println("<hr />");
        //w.println("<img src="gif/aa.jpg" />");
        w.println("</body>");
        w.println("</html>");
        w.flush();
    }  
}
结果是:
?????

二.看服务器传回浏览器的原始包
[第一部份,包头(以字串方式显示)]
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Wed, 22 Oct 2008 08:37:29 GMT


[第二部分,包体(以二进制方式显示)]
c7[第一个包体长度]
485454502F312E3120323030204F4B0D0A5365727665723A204170616368652D436F796F74652F312E310D0A436F6E74656E742D547970653A20746578742F68746D6C3B636861727365743D49534F2D383835392D310D0A5472616E736665722D456E636F64696E673A206368756E6B65640D0A446174653A205765642C203232204F637420323030382030383A33373A323920474D540D0A0D0A63370D0A3C68746D6C3E0D0A3C21444F43545950452068746D6C205055424C494320222D2F2F5733432F2F445444205848544D4C20312E30205374726963742F2F454E222022687474703A2F2F7777772E77332E6F72672F54522F7868746D6C312F4454442F7868746D6C312D7374726963742E647464223E0D0A3C686561643E0D0A3C7469746C653E3F3F3F3F3F3C2F7469746C653E0D0A3C2F686561643E0D0A3C626F64793E0D0A3F3F3F3F3F0D0A3C6872202F3E0D0A3C2F626F64793E0D0A3C2F68746D6C3E0D0A0D0A300D0A0D0A
0[第二个包体长度]

从Content-Type中看出包体的编码方式是ISO-8859-1,这是Servlet的默认编码方式.以ISO-8859-1来翻译第一个包体的内容:

<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x
html1/DTD/xhtml1-strict.dtd">
<head>
<title>?????</title>
</head>
<body>
?????
<hr />
</body>
</html>
三.原因
尽管我们在Servlet中设置了中文,但容器框架会把中文翻成ISO-8859-1编码,而ISO-8859-1并不支持中文,所以翻成了?????

四.解决
1.设置编码方式来解决问题:

public class SimpleServle
  相关解决方案