文章目录
SpringBoot国际化使用
SpringBoot在默认情况下是支持国际化使用的,首先需要在src/main/resources下新建国际化资源文件。
messages.properties(默认配置)
message = 欢迎使用国际化
messages_en_US.properties(英文配置)
message = Welcome to internationalization (English)
messages_zh_CN.properties(汉语配置)
message = \u6b22\u8fce\u4f7f\u7528\u56fd\u5316\uff08\u4e2d\u6587\uff09
然后进行i18n的配置,新建配置类i18nConfig,这个类需要继承WebMvcConfigurerAdapter类。localResolver方法中设置默认使用的语言类型,在localeChangeInterceptor()方法中设置识别类型的参数,并且从继承类中实现addInterceptors()方法,用于拦截locaeChangeInterceptor()方法,进而实现国际化。
i18nConfig
package com.sx.springdemo;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class I18nConfig extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.US);
return sessionLocaleResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(localeChangeInterceptor());
}
}
改造默认生成的启动类,注入MessageSource类获取国际化资源
@SpringBootApplication
@Controller
public class SpringdemoApplication {
@Autowired
private MessageSource messageSource;
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
@GetMapping("/")
public String hello(Model model){
Locale locale = LocaleContextHolder.getLocale();
model.addAttribute("message",
messageSource.getMessage("message", null, locale));
return "index";
}
在src/main/resources/tempate下新建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="/?lang=en_US">English(US)</a>
<a href="/?lang=zh_CN">简体中文</a></br>
<p><label th:text="#{message}"></label></p>
</body>
<html>
ref="/?lang=zh_CN">简体中文</a></br>
<p><label th:text="#{message}"></label></p>
</body>
<html>