Problems with UTF-8 encoding, JSP, jQuery, Spring

后端 未结 2 1585
死守一世寂寞
死守一世寂寞 2021-02-10 04:27

I have a web app with spring,jsp and jquery in a apache tomcat 6, one jsp page has a form that send the data with a ajax call made whit jquery, to a Spring MultiActionController

相关标签:
2条回答
  • 2021-02-10 05:11

    Everything looks fine until the point that you get the parameter in a variable. It's just your backend which still needs to be configured to use UTF-8. For example, the System.out.println() or the logger where you're sending the retrieved parameter to should also use UTF-8. Or the database where you're storing the retrieved parameter should also use UTF-8. Or the JDBC driver which is interacting with that DB. Or the text file where you're writing the data to. Etcetera.

    See also:

    • Unicode - How to get the characters right?

    Unrelated to your concrete problem, the line

    request.setCharacterEncoding("UTF-8");
    

    should be executed before Spring kicks in. It sets the POST request encoding and this will fail whenever Spring determines the request body before executing the action (note that this line has totally no effect on GET requests). Spring has a CharacterEncodingFilter which does exactly that. Register this in your web.xml:

    <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>
    
    0 讨论(0)
  • 2021-02-10 05:26

    I had the same problem from with Characters and I solved it the following way:

    request.setCharacterEncoding("utf-8");
                    StringBuffer requestContent = new StringBuffer();
                    do
                    {
                        bytesRead = request.getInputStream().readLine(bytes,0,bytes.length);
                        if(bytesRead > 0)
                        {
                            requestContent.append(new String(bytes,0,bytesRead,"UTF-8"));
                        }
                    }
                    while(bytesRead > 0);
    

    and then fetch from requestContent your string started with "name="

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