gpt4 book ai didi

java - Spring MVC : CharacterEncodingFilter; why only set response encoding by force?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:32 25 4
gpt4 key购买 nike

我正在查看 Spring MVC 提供的 CharacterEncodingFilter。我想知道为什么只有在请求编码被强制为给定编码时才能设置响应编码?如果在接受 header 字段中未指定任何内容,为什么不能设置默认响应编码?或者如果请求中没有编码?

代码:

@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

if (this.encoding != null && (this.forceEncoding
|| request.getCharacterEncoding() == null)) {

request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}

我找到这个作为引用 https://jira.springsource.org/browse/SPR-3328?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel声明只有在强制设置请求编码时才能设置响应编码。为什么?

提前致谢,马丁

最佳答案

我可以告诉您 Juergen Hoeller 在链接 https://jira.springsource.org/browse/SPR-3328?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel 上所说的话,

在 web.xml (Servlet 2.4+) 中添加以下过滤器以设置编码:

<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

编辑:

CharacterEncodingFilter :即使在 HTML 页面或表单中指定,当前浏览器通常也不会设置字符编码。如果请求尚未指定编码,则上述过滤器可以应用其编码,或者在任何情况下都强制执行此过滤器的编码(“forceEncoding”="true")。如果严格要对字符进行编码,则强制设置。

  1. why it was only possible to set the response encoding when the request encoding was forced to the given encoding?
  2. Why not be able to set a default response encoding if nothing is specified in the accept header fields? Or if no encoding was present in the request?

我认为 Boris 的 link在评论中将回答这些问题。

关于java - Spring MVC : CharacterEncodingFilter; why only set response encoding by force?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11685644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com