Junjie Junjie - 5 months ago 23
HTML Question

characters posted from browser encoded with "iso-8859-1" however it should be "UTF-8"

I want to get message from user's input on frontend website, the form posted should be encoded with "UTF-8", however, the spring mvc controller get the object encoded with "iso-8859-1", I have to convert all strings to "UTF-8" separately. It's really ugly and not convenient.

**Request Headers**
POST /feedback HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/feedback
**Form Data**
(Please ignore)
**Response Headers**

My controller is:

@RequestMapping(value = "/feedback", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public ModelAndView quizStart(@ModelAttribute("userComments") UserComments userComments) {
System.out.println(userComments.toString()); //*output 1*
try {
System.out.println(String.format("User comments: %s", new String(userComments.toString().getBytes("iso-8859-1"), "UTF-8"))); //*output 2*
} catch (UnsupportedEncodingException e) {
return new ModelAndView("user_feedback");

The output 1 is not expected because it's encoded with "iso-8859-1", output 2 is correct but it's almost impossible to convert all object to "UTF-8" one by one.

Could anyone help to provide a better solution other than convert the message one by one please ?

Thanks a lot.


I defined the encoding filter refer to this document. And it works.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

public class FiltersConfig {

    public CharacterEncodingFilter characterEncodingFilter() {
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        return characterEncodingFilter;