Search code examples
spring-bootspring-mvctomcatutf-8character-encoding

Spring Boot Umlaute in Redirect URL


2024 and still problems with encoding UTF-8. Here's my problem reduced to a very simple project with tests (just two important classes, rest is boilerplate created with Spring Initalizr):

https://github.com/kicktipp/springumlaut

I have a redirect in a SpringBoot App which contains an German Umlaut like "ö".

@GetMapping("/hallo")
public String hallo() {
    return "redirect:/hallöchen";
}

@ResponseBody
@GetMapping("/hallöchen")
public String helloWithUmlaut() {
    return "Hallöchen";
}

Running with the default Tomcat engine I get an status code 400 with the message

java.lang.IllegalArgumentException: Invalid character found in the request target [/hall0xc30xb6chen ]. The valid characters are defined in RFC 7230 and RFC 3986

The error is thrown in CoyoteAdapter in the method convertURI line 1068 and it says in the comment, that this should never happen:

// Should never happen as B2CConverter should replace
// problematic characters
request.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);

In my test where I call the URL with Umlaut directly everything works fine.

Why does not Spring Boot encode this URL properly, so everything works out-of-the-box and how can I fix it in the most easy and standard way?


Solution

  • As described in the comment, the literal parts of the redirect URL are not encoded automatically.

    For example, you can use RedirectAttributes to embed URI variables:

    @GetMapping("/hallo")
    public String hallo(RedirectAttributes attributes) {
      attributes.addAttribute("var", "hallöchen");
      return "redirect:/{var}";
    }
    

    or encode it by yourself:

    @GetMapping("/hallo")
    public String hallo() throws UnsupportedEncodingException {
      return "redirect:/" + URLEncoder.encode("hallöchen", "UTF-8");
    }