中文:
英文:
1 在resource添加配置文件(语言切换)
login.properties:默认显示的配置文件
login_en_US.properties:英文的配置文件
login_zh_CN.properties:中文的配置文件
点击resource Bundle视图化显示配置
2 在application.properties文件配置
#绑定配置文件的位置
spring.messages.basename=i18n.login
3 在thymeleaf的模板中使用语法
<!--表达式格式:#{...}-->
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<input type="checkbox" value="remember-me"> [[ #{login.remember} ]]
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.signin}]]</button>
4 点击"中文","English"进行切换
在html文件中,为"中文","English"的超链接添加链接请求
<!--在thymeleaf模板中参数使用"()"小括号-->
<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
5 在config文件中添加自己的LocaleResolver类并实现LocaleResolver接口重写方法
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取请求参数lang=en_US,lang=zh_CN
String lang = httpServletRequest.getParameter("lang");
//没有获取默认的
Locale locale = Locale.getDefault();
//不为空
if (!StringUtils.isEmpty(lang)){
//{国家,地区} {en,US} {zh,CN}
String[] split = lang.split("_");
//获取国际化的参数
locale = new Locale(split[0], split[1]);
}
//返回
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
5 在视图解析器中添加到bean
自定义视图解析器MyMvcConfig
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.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
//这样自定义的国家化组件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}