src\main\resources\i18n\messages_zh_CN.properties
message.hello=你好,世界!
message.welcome=欢迎!
src/main/resources/i18n/messages_en_US.properties
message.hello=Hello World!
message.welcome=Welcome!
默认语言
src\main\resources\i18n\messages.properties
message.hello=Hello World!
message.welcome=Welcome!
config
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
// 默认语言设置为英文
slr.setDefaultLocale(Locale.US);//ENGLISH
return slr;
}
// 如果还需要拦截器来处理locale切换请求
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
registry.addInterceptor(interceptor);
}
}
controller文章来源:https://www.toymoban.com/news/detail-818322.html
@Autowired
private MessageSource messageSource;
@GetMapping("/switch-language")
public String switchLanguage(@RequestParam("lang") String lang, HttpServletRequest request) {
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale(lang));
return "redirect:/";
}
@GetMapping("/")
public String home(Model model) {
Locale locale = LocaleContextHolder.getLocale();
model.addAttribute("helloMessage", messageSource.getMessage("message.hello", null, locale));
model.addAttribute("welcomeMessage", messageSource.getMessage("message.welcome", null, locale));
return "home";
}
在Thymeleaf模板中引用国际化消息:文章来源地址https://www.toymoban.com/news/detail-818322.html
<!-- home.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Internationalization Example</title>
</head>
<body>
<h1 th:text="#{message.hello}"></h1>
<p th:text="#{message.welcome}"></p>
<a th:href="@{/switch-language?lang=en_US}" th:text="English">English</a>
<a th:href="@{/switch-language?lang=zh_CN}" th:text="中文">中文</a>
</body>
</html>
来切换语言
switch-language?lang=zh_CN
switch-language?lang=en_US
到了这里,关于Spring Boot实现国际化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!