Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 forced to the given encoding? 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?

The code:

@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);
}

I found this as reference https://jira.springsource.org/browse/SPR-3328?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel stating that the response encoding can only be set when the request encoding is forcibly set. Why?

Thanks in advance, Martin

like image 353
Martin Becker Avatar asked Jul 27 '12 10:07

Martin Becker


1 Answers

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.

like image 162
Nandkumar Tekale Avatar answered Oct 05 '22 23:10

Nandkumar Tekale