Splash
Splash

Reputation: 1288

Why this Spring MVC controller returns corrupted UTF-8 String?

I have modified so many places to make my Spring MVC work with UTF-8, including a char filter, contextType in jsp, and fixed MySQL as well, so my project is working perfectly with UTF-8.

However, this newly added function wouldn't get it right

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public @ResponseBody
String uploadFileHandler(
        @RequestParam("name") String name,
        @RequestParam("type") String type,
        @RequestParam("file") MultipartFile file//, HttpServletResponse response
        ) throws IOException {
//      response.setCharacterEncoding("UTF-8");
        if (file.isEmpty())
            return "Empty";

As you can see, I have put procudes, and setCharacterEncoding. The returned String is used in Ajax and I have

        var ajax = new XMLHttpRequest();
        ajax.overrideMimeType('text/xml;charset=UTF-8');

Here is the beginning of the form in jsp

<form name = "myForm" method="POST" onsubmit="return validateForm()" enctype="multipart/form-data">

But my webpage still shows ????. So what else am I missing? I don't have JQuery, so hoping a solution without using it unless a must.

Upvotes: 1

Views: 8576

Answers (3)

Mohammad Badiuzzaman
Mohammad Badiuzzaman

Reputation: 748

Put in config

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

In controller mapping you can add

produces = "text/plain;charset=UTF-8"

but not

produces = "text/html;charset=UTF-8"

For example: GetMapping () to force ResponseBody output encoding UTF-8

@GetMapping(value = "/oith/getProcess", produces = "text/plain;charset=utf-8")
public @ResponseBody
ResponseEntity<String> getProcess(@RequestParam(value = "module") BigInteger moduleId) {
    return new ResponseEntity<>("any text...", HttpStatus.CREATED);
}

Upvotes: 0

Nebula Era
Nebula Era

Reputation: 263

Found this link about ResponseBody problem with return UTF-8 string due to Spring web "bug"

Summary:

  1. set org.springframework.web.filter.CharacterEncodingFilter in web.xml to enforce UTF-8
  2. set <value>text/plain;charset=UTF-8</value> in spring-servlet.xml
  3. StringHttpMessageConverter problem eliminated by creating own class

Upvotes: 2

martian111
martian111

Reputation: 593

Not sure how you've configured your Maven project (if you are even using that) and web.xml, but the answers to the following question helped me in the past:

Upvotes: 2

Related Questions