springboot 国际化

 

Spring Boot在默认情况下是支持国际化使用的,首先需要在src/main/resources下新建国际化资源文件,这里为了举例说明,分别创建如下三个文件:

• messages.properties(默认配置)

message=欢迎使用国际化(默认)

• messages_en_US.properties(英文配置)

message=Welcome to internationalization (English)

• messages_zh_CN.properties(汉语配置)

message=欢迎使用国际化(中文)

 

进行i18n的配置,新建配置类i18nConfig

复制代码
@Configuration
public class i18nConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认使用的语言
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名 用于区别使用语言类型
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}
复制代码

 

在类上加入SpringMVC注解@Controller,注入MessageSource类获取国际化资源,并且创建方法返回资源文件对应的数据,返回到前台。

复制代码
@Controller
public class HelloController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/templates/index")
    public String index(Model model) {
        Locale locale = LocaleContextHolder.getLocale();
        model.addAttribute("message", messageSource.getMessage("message", null, locale));
        return "index";
    }
}
复制代码

 

在src/main/resources/template下新建index.html

复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/templates/index?lang=en_US">English(US)</a>
<a href="/templates/index?lang=zh_CN">简体中文</a></br>
<p><label th:text="#{message}"></label></p>
</body>
</html>
复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

 

访问:

http://127.0.0.1:8081/templates/index

 

源码:https://gitee.com/caoyeoo0/xc-springboot/tree/%E5%9B%BD%E9%99%85%E5%8C%96/

 

posted @   草木物语  阅读(334)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2019-11-26 java 迭代的陷阱
点击右上角即可分享
微信分享提示