代码之家  ›  专栏  ›  技术社区  ›  Filipe Miguel Fonseca

Servlet和jsp字符编码特性

  •  2
  • Filipe Miguel Fonseca  · 技术社区  · 14 年前

    我有一个webapp,需要在上面显示unicode字符。当我在jsp中编写字符串时一切都很好,例如:

    <%@ page contentType="text/html;charset=UTF-8" %>
    <%@ page import="com.xyz.foo.ConsoleApp" %>
    <html>
        <head>
            <meta charset="UTF-8"/>
        </head>
        <body><%= "Setúbal" %></body>
    </html>
    

    我得到想要的输出:

    但是,servlet中的等效代码无法正确呈现,例如:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
    
        writer.println("<html>");
        writer.println("<head><meta charset='UTF-8'/></head>");
        writer.println("<body>Setúbal</body>");
        writer.println("</html>");
    }
    

    当我在jsp中从类加载文本时,也会发生同样的情况:

    <%@ page contentType="text/html;charset=UTF-8" %>
    <%@ page import="com.xyz.foo.ConsoleApp" %>
    <html>
        <head>
            <meta charset="UTF-8"/>
        </head>
        <body><%= ConsoleApp.getText() %></body>
    </html>
    

    塞图巴尔

    Content-Type    text/html; charset=utf-8
    Content-Encoding    gzip
    Date    Tue, 09 Nov 2010 09:44:05 GMT
    Server  Google Frontend
    Cache-Control   private, x-gzip-ok=""
    Content-Length  438
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Christoffer Hammarström    14 年前

    使用 javac -encoding 参数来告诉javac您的java源代码存储在什么中,否则它使用的平台默认值显然不是UTF-8。