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!
默認(rèn)語言
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();
// 默認(rèn)語言設(shè)置為英文
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文章來源:http://www.zghlxwxcb.cn/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模板中引用國際化消息:文章來源地址http://www.zghlxwxcb.cn/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
到了這里,關(guān)于Spring Boot實(shí)現(xiàn)國際化的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!