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

前端 未结 2 1008
时光说笑
时光说笑 2021-02-09 19:46

I was having a look at the CharacterEncodingFilter provided by Spring MVC. I was wondering why it was only possible to set the response encoding when the request encoding was fo

相关标签:
2条回答
  • 2021-02-09 20:02

    If nothing else works, you can create a filter ( bean ) in security-Context.xml and set forceEnconding=true;

    <bean id="characterEncodingFilter" class="org.springframework.web.filter.CharacterEncodingFilter">
        <property name="encoding" value="utf-8"></property>
        <property name="forceEncoding" value="true"></property>
    </bean>
    

    Don't forget to set the new custom-Filter:

    <security:custom-filter ref="characterEncodingFilter" after="FIRST"/>
    
    0 讨论(0)
  • 2021-02-09 20:04

    I can tell you what Juergen Hoeller says on link https://jira.springsource.org/browse/SPR-3328?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel,

    Add following filter in web.xml (Servlet 2.4+) to set encoding :

    <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>
    

    EDIT :

    CharacterEncodingFilter : Current browsers typically do not set a character encoding even if specified in the HTML page or form. The above filter can either apply its encoding if the request does not already specify an encoding, or enforce this filter's encoding in any case("forceEncoding"="true"). If we strictly want to encode characters, we set it forcibly.

    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?

    I think Boris's link in comment will answer these questions.

    0 讨论(0)
提交回复
热议问题