UTF-8 encoding with form post and Spring Controller

前端 未结 3 1745
轮回少年
轮回少年 2021-01-11 21:13

I am trying to submit a form, which has UTF8 characters inside it. The form looks like this:

相关标签:
3条回答
  • 2021-01-11 21:51

    I would suggest you remove the CharacterEncodingFilter, which may itself be the cause of double encoding.

    To debug the situtation, you should first check if the browser is posting the data correctly. Use Firebug (for Firefox) or developer tools on Chrome (F12)

    Most likely, the problem is at the server side. Which server do you use? If you use Tomcat, you need to set the CharsetEncoding to UTF-8 on the Connector element in server.xml

    Update 1:

    It looks very likely that the problem is the forceEncoding that you are setting. As per the docs

    This 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")

    When you do a get, there is no encoding specified, so it makes sense that it works.

    However when you do the POST, the encoding is already applied and then (it seems) is applied again because of the forceEncoding=true

    0 讨论(0)
  • 2021-01-11 21:55

    Looks like browsers don’t send the charset as part of Content-Type in request headers (even when accept-charset on form is set) and Tomcat deals with body of such requests as Latin-1 ( http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q1 ).

    So at a later point this might have been decoded as Latin-1 and encoded as UTF-8 resulting in garbled up characters.

    Moving CharacterEncodingFilter to the top and forcing the encoding to be set as UTF-8 solved the problem.

    0 讨论(0)
  • 2021-01-11 22:06

    Do you have a filter-mapping entry in your web.xml for EncodingFilter?

    <filter-mapping>
      <filter-name>EncodingFilter</filter-name>
      <url-pattern>*</url-pattern>
    </filter-mapping>
    
    0 讨论(0)
提交回复
热议问题