Home > Blockchain >  Tomcat Spring Rest Wrong Encoding
Tomcat Spring Rest Wrong Encoding

Time:11-25

currently, I am working on a Spring Rest Endpoint (not Spring Boot) which I deploy to a Tomcat Servlet Container. It takes a Multipart form

@PostMapping(value = "/audit/{auditNumber}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadFileForAudit(//
        @PathVariable String peNumber, //
        @RequestParam("category") String category, //
        @RequestParam("documents") MultipartFile file, //
        @RequestParam("description") String description, //
        @RequestHeader Map<String, String> headers) {


    
    System.out.println("category " category);
    System.out.println("description " description);

When German Umlauts are sent as category or description, the console output looks like this:

category Prüfungsanordnung
description öäü

I have other Rest Resources, but they are working. Somehow this Resource has the wrong encoding. I suspect the Multipart-form to be the problem.

The frontend is not the problem. I can use JavaScript fetch or Postman and both have the same result.

Any hint is appreciated.

CodePudding user response:

For PostMapping you can't use URIEncoding="UTF-8" so instead of that you can define a filter to tell Tomcat that your request encoding is UTF-8, either you can add this to web.xml:

<filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

or add this filter :

public class EncodingFilter implements Filter {
    private String encoding = "UTF-8";

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        if (config.getInitParameter("encoding") != null) {
            encoding = config.getInitParameter("encoding");
        }
    }
}
  • Related