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
相关推荐
Slow菜鸟4 小时前
Java开发规范(五)| 接口设计规范—前后端/跨服务协作的“架构级契约”
java·状态模式·设计规范
草原印象4 小时前
Spring Boot Spring MVC MyBatis MyBatis Plus框架编写项目实战案例
spring boot·spring·mybatis·springmvc·mybatisplus
p***s914 小时前
Spring Boot 整合 Redis 步骤详解
spring boot·redis·bootstrap
Slow菜鸟4 小时前
SpringBoot教程(三十五)| SpringBoot集成TraceId(追踪ID)
java·spring boot·后端
__万波__4 小时前
二十三种设计模式(二)--工厂方法模式
java·设计模式·工厂方法模式
汤姆yu4 小时前
基于SpringBoot的餐饮财务管理系统的设计与实现
java·spring boot·后端
3***31214 小时前
Spring Boot 整合 MyBatis 与 PostgreSQL 实战指南
spring boot·postgresql·mybatis
czc1314 小时前
4K QPS 博客社区:CCBlog 全栈开源,Springboot项目实战,Docker一键部署
spring boot·redis·docker·开源·vue·rabbitmq
q***31144 小时前
【JAVA进阶篇教学】第十二篇:Java中ReentrantReadWriteLock锁讲解
java·数据库·python