Spring MVC 和 UTF-8:如何使用瑞典语特殊字符?

问题描述 投票:0回答:2
java spring spring-mvc utf-8 character-encoding
2个回答
3
投票

您的屏幕截图表明您的搜索关键字 bäck 作为 URL 的一部分作为 URL 参数发送。它还表明这项工作似乎正确地采用了 UTF-8 URL 编码。您在调试器中返回的字符串是典型的 UTF-8 编码字节的 ISO-Latin 解码:例如HTTPServletRequest 解析器使用 ISO-Latin 解析 UTF-8 编码的字符串。

因此,您的 ServletFilter 对解释它没有任何帮助:

request.setCharacterEncoding(this.encoding);
response.setCharacterEncoding(this.encoding);

因为正如 javadoc 所说:这些方法适用于 HTTP 请求的正文,而不是其 URL。

/**
 * Overrides the name of the character encoding used in the body of this
 * request. This method must be called prior to reading request parameters
 * or reading input using getReader(). Otherwise, it has no effect.
 * 

查看 URL 参数解析是 Servlet 容器的职责,您应该查看的设置可能是容器级别的设置。 例如,在 Tomcat 上,如文档中所述: http://tomcat.apache.org/tomcat-7.0-doc/config/http.html :

URIEncoding :指定在 %xx 解码 URL 后用于解码 URI 字节的字符编码。如果未指定,将使用 ISO-8859-1。

默认情况下,它使用 ISO-8859-1。您应该将其更改为 UTF-8,然后,您的请求参数将从 servlet 容器中正确解析,并传递给 HTTPServletRequest 对象。

编辑:当您看到浏览器行为不一致时,您可以检查 HTML 表单的一致性。请确保

  1. 您的 HTTP Content-Type 标头和定义字符集的 HTML“元”标记在声明字符集时都存在且一致。 (考虑到您的 servlet 过滤器,它们都应该是 UTF-8)
  2. 您实际上尊重响应正文中的字符集声明(您实际上从 JSP 中写入 UTF-8 字符串 - 或其他任何内容)

0
投票

问题:如果服务部署在docker容器中,如何处理瑞典字符。

按照以下步骤处理瑞典字符:

  1. 请求映射中的端点使用以下属性

           produces = {"application/json;charset=UTF-8", "application/json;charset=UTF-8"}
    
  2. 在 application.properties 中插入以下行

spring.http.encoding.charset=UTF-8

spring.http.encoding.enabled=true

spring.http.encoding.force=true

  1. 在容器中安装语言环境,添加以下行

运行 apt-get -y 安装语言环境

设置区域设置,您可以更改为 sv_SE 但以下操作也将起作用,因为它启用了 UTF-8

RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \

locale-gen

ENV LANG en_US.UTF-8

ENV 语言 en_US:en

ENV LC_ALL en_US.UTF-8

  1. 在主类中添加语言环境:

导入java.util.Locale;

Locale locale = new Locale.Builder().setLanguage("sv").setRegion("SE").build();

Locale.setDefault(区域设置)

© www.soinside.com 2019 - 2024. All rights reserved.