Spring Boot实现国际化

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

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

<!-- 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有知识的山巅

文章对你有用,学到了知识。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值