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
相关推荐
西凉的悲伤5 分钟前
java 使用PNG图片隐写文件
java·图片隐写·png
有梦想的小何8 分钟前
Cursor AI 编程实战(篇一):Prompt 与案例总结
java·linux·prompt·ai编程
河阿里28 分钟前
SpringBoot:Spring Task定时任务完整使用教学
java·spring boot·spring
jiayong2328 分钟前
Tool Permission 与 Sandbox 的安全流水线:Agent 工具系统的工程边界
java·数据库·安全·agent
rururunu37 分钟前
Windows 下切换 Java 环境太复杂了,我做了个 cli 工具,可以快速安装,切换 Java 版本
java
qq_4523962339 分钟前
第十一篇:《性能压测基础:JMeter线程模型与压测策略设计》
java·开发语言·jmeter
传说之后41 分钟前
深入浅出 Raft:万字解析分布式共识的核心设计
后端
澈2071 小时前
二叉搜索树:高效增删查的秘诀
java·开发语言·算法
小小小小宇1 小时前
Go 后端高并发架构:从外到内的立体防御体系
后端