之前沒有考慮過如何實現(xiàn)國際化,在這次的香港項目中误阻,客戶要求繁體切換簡體功能熔掺,有了這篇文章。
快速入門
第一步:構(gòu)建一個基礎(chǔ)的Spring Boot應(yīng)用
第二步:在pom.xml中引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
第三步:創(chuàng)建應(yīng)用主類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第四步:配置文件resources下新建文件夾
welcome=hello welcome
注意必須是messages打頭
第五步:創(chuàng)建國際化配置文件叭披,繼承WebMvcConfigurationSupport
/**
* Description:
* @date 2018.06.05 9:16
*/
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
/**
* cookie區(qū)域解析器
*
* @return
*/
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver slr = new CookieLocaleResolver();
//設(shè)置默認(rèn)區(qū)域,
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
slr.setCookieMaxAge(3600);//設(shè)置cookie有效期.
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 設(shè)置請求地址的參數(shù),默認(rèn)為:locale
lci.setParamName(LocaleChangeInterceptor.DEFAULT_PARAM_NAME);
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
application.yml文件配置
spring:
messages:
basename: i18n/messages
encoding: UTF-8
cache-seconds: 3600
第六步:MessageSource類可以獲取messages的內(nèi)容。
@Component
public class LocaleMessageSourceUtil {
@Resource
private MessageSource messageSource;
public String getMessage(String code) {
return getMessage(code, null);
}
/**
*
* @param code :對應(yīng)messages配置的key.
* @param args : 數(shù)組參數(shù).
* @return
*/
public String getMessage(String code, Object[] args){
return getMessage(code, args, "");
}
/**
*
* @param code :對應(yīng)messages配置的key.
* @param args : 數(shù)組參數(shù).
* @param defaultMessage : 沒有設(shè)置key的時候的默認(rèn)值.
* @return
*/
public String getMessage(String code,Object[] args,String defaultMessage){
//這里使用比較方便的方法,不依賴request.
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(code, args, defaultMessage, locale);
}
}
第七步:前端調(diào)用HelloController.java
@Controller
public class HelloController {
@Autowired
private LocaleMessageSourceUtil messageSourceUtil;
@RequestMapping("/hello")
public String hello() {
String welcome = messageSourceUtil.getMessage("welcome");
System.out.println(welcome);
return "hello";
}
}
第八步:http調(diào)用測試
參數(shù)locale= en_US,返回英文
參數(shù)locale=zh_CN ,返回簡體中文