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/

原文地址:https://www.cnblogs.com/ooo0/p/14042950.html