从 Servlet 在 JSP 页面中显示 UTF-8 文本

Chr*_*ian 2 java jsp

当我尝试通过在 JSP 上显示德语文本(例如 Zur\xc3\xbccksetzen)时request.setAttribute(),它显示为Zur\xef\xbf\xbdcksetzen

\n\n
request.setAttribute("test", "Zur\xc3\xbccksetzen");\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的 JSP 页面将 contentType 定义为 UTF-8:

\n\n
<%@ page contentType="text/html;charset=UTF-8" %>\n<!DOCTYPE html>\n<html lang="en">\n<head>\n    <meta charset="UTF-8">\n
Run Code Online (Sandbox Code Playgroud)\n\n

我只是用 来显示该属性${test}

\n\n
\n\n

如果我将请求转发到 JSP 页面而不是包含 JSP,文本将正确显示

\n\n

转发(工作):
\nrequest.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);

\n\n

包含(不起作用):
\nrequest.getRequestDispatcher("/WEB-INF/views/index.jsp").include(request, response);

\n\n
\n\n

我的 IDE 使用 UTF-8

\n\n

在此输入图像描述

\n

Chr*_*ian 5

回答我自己的问题:

正如JSP 全球化支持中所述,默认值如下

The default MIME type is text/html for traditional JSP pages; it is text/xml for JSP XML documents.

The default for the page source character encoding (for translation) is ISO-8859-1 (also known as Latin-1) for traditional JSP pages; it is UTF-8 or UTF-16 for JSP XML documents.

The default for the response character encoding is ISO-8859-1 for traditional JSP pages; it is UTF-8 or UTF-16 for JSP XML documents.

The determination of UTF-8 versus UTF-16 is according to "Autodetection of Character Encodings" in the XML specification, at the following location
Run Code Online (Sandbox Code Playgroud)

所以ServletJSP页面是默认的ISO-8859-1

request.getRequestDispatcher("/WEB-INF/views/index.jsp").include(request, response);
当您使用.includeJSP 页面时,如上所示,该页面将使用默认字符编码 (ISO-8859-1) 进行编码。为了使用 UTF-8 编码,您必须设置response.setCharacterEncoding("UTF-8");注意:JSP 中的 ContentType 指令将被忽略。

request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
当您.forward访问 JSP 页面(如上所述)或直接从浏览器访问 JSP 页面时,该页面将使用默认字符编码 (ISO-8859-1) 进行编码。为了使用UTF-8编码,您必须添加为JSP页面的第一行<%@ page contentType="text/html; charset=UTF-8" %>