Junjie
Junjie

Reputation: 1175

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**
Content-Language:zh-CN
Content-Type:text/html;charset=UTF-8

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) {
        e.printStackTrace();
    }
    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.

Upvotes: 4

Views: 6639

Answers (2)

Bahadir Tasdemir
Bahadir Tasdemir

Reputation: 10783

If you need to convert your String between UTF-8 and ISO-8859-1 check my answer here.

Upvotes: 0

Junjie
Junjie

Reputation: 1175

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;

@Configuration
public class FiltersConfig {

    @Bean
    public CharacterEncodingFilter characterEncodingFilter() {
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }

}

Upvotes: 4

Related Questions