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
相关推荐
xjz184217 分钟前
Rust 注释:从 // 到 rustdoc
后端
阿达和自己44 分钟前
springboot学习-springboot引入MyBatis-Plus
spring boot·学习·mybatis
Lansonli1 小时前
大数据Spark(八十八):Spark任务资源之Standalone集群测试
java·服务器·spark
syyjhchou2 小时前
自己搭企业内部中转站,怎么让请求更容易命中缓存
人工智能·后端·语言模型·aigc
budingxiaomoli2 小时前
Spring AOP
java·spring·java-ee
特立独行的猫A2 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
nice_lcj5202 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
SomeOtherTime2 小时前
Rust集合(AI回答)
开发语言·后端·rust
文丑颜不良啊3 小时前
LeetCode2741~2760题目解析
java·leetcode
我不会起名字3223 小时前
req.Seqs[len-1]:空切片防御缺口与 RPC 二次校验
后端·mongodb·go·即时通讯·im·故障排查