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
相关推荐
派大鑫wink1 天前
【Day7】构造方法与 this 关键字:初始化对象的正确姿势
java·开发语言
JIngJaneIL1 天前
基于java+ vue办公管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
uzong1 天前
如何将项目做出 owner 的感觉
后端
超级大只老咪1 天前
速通:类,对象,方法(Java)
java
毕设源码-郭学长1 天前
【开题答辩全过程】以 基于SpringBoot的企业销售合同管理设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
while(1){yan}1 天前
JVM八股文
java·开发语言·jvm·java-ee
jiayong231 天前
Spring AI Alibaba 深度解析(一):框架概述与核心功能
java·人工智能·spring
AAA简单玩转程序设计1 天前
Java 异常处理:3 个 “避坑神操作”,告别崩溃式报错
java
徐老总1 天前
圆形(Circle)和矩形(Rectangle)两个样例类
java
一只努力的微服务1 天前
【Calcite 系列】将 INTERSECT 转换为 EXISTS
java·calcite