目錄
Locale:區域信息對象
LocaleResolver:獲取區域信息對象
SpringBoot國際化
步驟:
1、需要有進行國際化的html文件
2、編寫國際化配置文件
3、html中取國際化配置文件的值
4、application.properties中開啓國際化
實現:
1、需要有進行國際化的html文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>國際化測試</title>
</head>
<body>
<h3>中文</h3>
<hr />
</body>
</html>
2、編寫國際化配置文件
在resource包下,創建i18n包,建立三個文件
index.properties(默認)
#默認顯示
value=中文
index_zh_CN.properties(中文)
#中文
value=中文
index_en_US.properties(英文)
#英文
value=englist
3、html中取國際化配置文件的值
4、application.properties中開啓國際化
spring.messages.basename=i18n.index
測試:
默認效果
切換英文,選擇United States放在首位,刷新鏈接
IDEA比eclipse方便很多(我用的是IDEA開發,eclipse練習)
添加鏈接切換國際化
步驟:
前面的編寫國際化配置文件和在application.properties開啓國際化兩步不能少
1、html文件加鏈接
2、編寫自己MyLocaleResolver,實現LocaleResolver,從鏈接中獲取區域信息,並設置到Locale中
3、註冊自己的LocaleResolver組件
實現:
1、html文件加鏈接
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>國際化測試</title>
</head>
<body>
<h3 th:text="#{value}">中文</h3>
<p></p>
<a th:href="@{/index.html(l='zh_CN')}">中文</a>
<a th:href="@{/index.html(l='en_US')}">English</a>
<hr />
</body>
</html>
2、編寫自己MyLocaleResolver,實現LocaleResolver,從鏈接中獲取區域信息,並設置到Locale中
package com.test.component;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
/**
* 國際化鏈接處理文件
* @author xuexue
*
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
//獲取鏈接國際語言信息
String l = request.getParameter("l");
//得到默認的國際語言信息
Locale locale = Locale.getDefault();
//如果不爲空,則處理鏈接,根據鏈接選擇語言進行國際化
if (!StringUtils.isEmpty(l)) {
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
// TODO Auto-generated method stub
}
}
3、註冊自己的LocaleResolver組件
package com.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.test.component.MyLocaleResolver;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//跳轉到主頁
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
/**
* 註冊自己的國際化組件
* @return
*/
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
}
測試:
點擊英文