【发布时间】:2020-07-07 18:48:15
【问题描述】:
我正在尝试创建一个网页,该网页根据用户的位置以不同的语言显示文本。为此,我使用属性文件和要以每种语言显示的字符串,并将它们作为资源包加载,然后将这些字符串添加到模型中,以便我可以在 Thymeleaf 中访问它们。这是我的代码:
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model, Locale locale) {
ResourceBundle rb = ResourceBundle.getBundle("lang/index", locale);
addResourceBundleToModel(model, rb);
System.out.println(model.getAttribute("test2"));
return "index";
}
private void addResourceBundleToModel(Model model,
ResourceBundle resourceBundle) {
for (String key : resourceBundle.keySet()) {
model.addAttribute(key, resourceBundle.getString(key));
}
}
}
还有百里香文件:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a th:text ="#{test2}"></a>
</body>
</html>
当我加载页面并将model.getAttribute("test2") 打印到控制台时,我得到了我想要的字符串,即“abc”作为测试字符串。但是“abc”没有显示在浏览器中,而是我得到??test2_en_US??。我的代码有什么问题?如何让它在浏览器上显示“abc”?另外,我尝试使用@RestController 注释并返回model.getAttribute("test2").toString(),这样我就可以在浏览器上显示“abc”,但我无法让它与 Thymeleaf 一起使用。
【问题讨论】:
标签: java spring spring-boot spring-mvc thymeleaf