Spring Boot实现国际化

java 复制代码
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

java 复制代码
@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

java 复制代码
@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模板中引用国际化消息:

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
相关推荐
草履虫建模12 分钟前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
qq_297574673 小时前
【实战教程】SpringBoot 实现多文件批量下载并打包为 ZIP 压缩包
java·spring boot·后端
老毛肚3 小时前
MyBatis插件原理及Spring集成
java·spring·mybatis
学嵌入式的小杨同学3 小时前
【Linux 封神之路】信号编程全解析:从信号基础到 MP3 播放器实战(含核心 API 与避坑指南)
java·linux·c语言·开发语言·vscode·vim·ux
lang201509283 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
Re.不晚3 小时前
Java入门17——异常
java·开发语言
缘空如是3 小时前
基础工具包之JSON 工厂类
java·json·json切换
追逐梦想的张小年4 小时前
JUC编程04
java·idea
好家伙VCC4 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
南极星10054 小时前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言