我尝试在我的数据库中查找带有特殊瑞典语字符“bäck”的单词, 我有一个 jsp 页面:
<%@ page pageEncoding="utf-8" contentType="text/html; charset=utf-8" %>
...
<form name="mainform" action="/web/admin/users/">
<input id="keywords" type="text" name="keywords" size="30"
value="${status.value}" tabindex="1" />
<button class="link" type="submit">Search</button>
</form>
过滤器:
public class RequestResponseCharacterEncodingFilter extends OncePerRequestFilter {
private String encoding;
private boolean forceEncoding;
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setCharacterEncoding(this.encoding);
response.setCharacterEncoding(this.encoding);
filterChain.doFilter(request, response);
}
}
web.xml
<web-app ...>
...
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>test.testdomain.spring.RequestResponseCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
当我开始找到“bäck”这个词时,它看起来像这样bäck
。请求被编码为 UTF-8:
但就在我退出调试器过滤器中的 doFilterInternal
方法之前,我看到:
我做错了什么?为什么文本没有编码为 UTF-8?
编辑:这很奇怪,我刚刚尝试在 Chrome 和 Mozilla Firefox 中查询,效果很好,所以在我看来,我只在 Internet Explorer 中遇到这个问题
编辑:Internet Explorer 给我这个字符串:b%C3%A4ck
但 Mozilla Firefox 和 Chrome 给我这个字符串:b%E4ck
>。它们显然不同,为什么呢?
最佳答案
您的屏幕截图表明您的搜索关键字 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 : This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
默认情况下,它使用 ISO-8859-1。您应该将其更改为 UTF-8,然后,您的请求参数将从 servlet 容器中正确解析,并传递给 HTTPServletRequest 对象。
编辑:当您看到浏览器行为不一致时,您可以检查 HTML 表单的一致性。请确保
- 您的 HTTP Content-Type header 和定义字符集的 HTML“元”标记在声明字符集时都存在且一致。 (考虑到您的 servlet 过滤器,它们都应该是 UTF-8)
- 您实际上尊重响应正文中的字符集声明(您实际上从 JSP 中写入 UTF-8 字符串 - 或其他任何内容)
关于java - Spring MVC 和 UTF-8 : How to work with Swedish special characters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25057157/