重定向 URL 中的 Spring Boot 变音符号

问题描述 投票:0回答:1

2024 年,UTF-8 编码仍然存在问题。这是我的问题简化为一个带有测试的非常简单的项目(只有两个重要的类,其余的是使用 Spring Initalizr 创建的样板):

https://github.com/kicktipp/springumlaut

我在 SpringBoot 应用程序中有一个重定向,其中包含像“ö”这样的德语变音符号。

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

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

使用默认 Tomcat 引擎运行时,我收到状态代码 400 和消息

java.lang.IllegalArgumentException:在 请求目标[/hall0xc30xb6chen]。有效字符已定义 在 RFC 7230 和 RFC 3986 中

该错误在方法 ConvertURI 第 1068 行中的

CoyoteAdapter
中抛出,并在注释中指出,这永远不应该发生

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

在我的测试中,我直接使用 Umlaut 调用 URL,一切正常。

为什么 Spring Boot 没有正确编码这个 URL,所以一切都是开箱即用的,我怎样才能以最简单和标准的方式修复它?

spring-boot spring-mvc tomcat utf-8 character-encoding
1个回答
0
投票

注释中所述,重定向 URL 的文字部分不会自动编码。

例如,您可以使用

RedirectAttributes
来嵌入 URI 变量:

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

或者自己编码:

@GetMapping("/hallo")
public String hallo() throws UnsupportedEncodingException {
  return "redirect:/" + URLEncoder.encode("hallöchen", "UTF-8");
}
© www.soinside.com 2019 - 2024. All rights reserved.