gpt4 book ai didi

java - URL问题中的Spring和德文字母

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:00 25 4
gpt4 key购买 nike

我在尝试将用户从登录页面(Spring)重定向到包含特殊德语字母(ä、ö、ü、ß)的网址时遇到此问题。这可能不仅限于他们,但目前这些很重要。工作流程如下所示:

  • 用户使用redirectUrl请求参数访问登录页面,例如:http://www.example.com/login.do?redirectUrl=http%3A%2F%2Fwww.example.com%2F%25C3%25B6l%2F,其中%25C3%25B6l转换为öl
  • 成功登录后,用户应重定向至 http://www.example.com/öl/。然而,由于某些奇怪的原因,实际的 URL 是 http://www.example.com/�l/

查看 URL 重定向跟踪,似乎(Spring?)将 ö 编码为 %F6 (Unicode?),而不是 %C3%B6 (UTF-8)。

spring 容器(Tomcat)全部设置为 UTF-8 编码。我还尝试过对 ISO-8859-1UTF-8 之间的 URL 进行编码和解码,但没有成功。

我也尝试过并且似乎有效的是手动将特殊字母转换为其 UTF-8 编码(例如 string.replace("ö", "%C3%B6");" 并以该形式传递 url。但是,这很丑陋,我不想这样做。

关于如何正确处理这个问题有什么建议吗?

谢谢。

最佳答案

假设您处于 Spring MVC 应用程序的上下文中,可以使用 RedirectView 来实现重定向。或者简单地使用前缀 redirect:作为 Controller 方法的返回值。将其捕获为 RequestParam在表单初始化期间并将其保留在 session 中,如下例所示:

型号:

public class LoginForm implements Serializable {

private String username;
private String password;
private String redirectUrl;
// getters and setters omitted
}

查看:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form:form method="POST" modelAttribute="loginForm" acceptCharset="UTF-8" action="login/doLogin">
<table>
<tr>
<td><form:label path="username">User Name</form:label></td>
<td><form:input path="username"/></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password"/></td>
</tr>
</table>
<div>
<input type="submit" value="Submit"/>
</div>
</form:form>
</body>
</html>

Controller :

@Controller
@RequestMapping("login")
@SessionAttributes(LoginController.FORM_NAME)
public class LoginController {

static final String FORM_NAME = "loginForm";
private static final String DEFAULT_REDIRECT_URL = "https://google.com";

@ModelAttribute(FORM_NAME)
public LoginForm createForm() {
return new LoginForm();
}

@GetMapping
public String showForm(Model model, @ModelAttribute(FORM_NAME) LoginForm loginForm, @RequestParam(required = false) String redirectUrl) {
loginForm.setRedirectUrl(redirectUrl);
model.addAttribute(FORM_NAME, loginForm);
return "login/login-form";
}

@PostMapping("/doLogin")
public String processFormCredentials(LoginForm loginForm) {
// input validation omitted ...
return "redirect:" + (loginForm.getRedirectUrl() != null ? loginForm.getRedirectUrl() : DEFAULT_REDIRECT_URL);
}
}

使用此代码,带有变音符号的重定向在 Tomcat 上运行良好 - http://<url>/login?redirectUrl=http%3A%2F%2Fwww.example.com%2F%25C3%25B6l%2F表单提交时重定向至 http://www.example.com/öl/

关于java - URL问题中的Spring和德文字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com