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

标签 java spring character-encoding

我正在查看 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/

相关文章:

java - 递归 Karatsuba 乘法不起作用?

python - 在pycharm控制台中为pipenv项目设置适当的字符编码

java - Jython - 尝试连接到数据库会导致 java.sql.SQLException : No suitable driver found

spring - 在 spring 上下文中定义一个字符串

spring - 配置文件未从 tomcat 中设置的环境变量中选取,但在 web.xml 中提及时选取

使用 Spring Boot 时未初始化 java.lang.IllegalStateException LifecycleProcessor 和 ApplicationEventMulticaster

Java file.encoding 读取 UTF-8 文件并处理 UTF-8 字符串

java - 解析编码为 UTF-8 和 UTF-16 的 XML 文件时出错

java - 微调器,添加向上/向下箭头按钮监听器

java - Ubuntu 内核杀死 java 进程,即使它没有内存不足