废话少说,直接讲解实现步骤:
1.编写国际化资源文件:
2.在核心配置文件(application.properties)中加入下面的话:
spring.messages.basename=i18n.login
3.将页面文字改为获取国际化配置,格式#{key}
<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}" placeholder="Username" required="" autofocus="">
<input type="password" class="form-control" th:placeholder="#{login.password}" placeholder="Password" required="">
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
点击连接切换语言怎么实现?
1.修改页面,点击连接携带语言参数
<a class="btn btn-sm" href="?l=zh_CN">中文</a>
<a class="btn btn-sm" href="?l=en_US">English</a>
2.实现区域信息解析器,并配到ioc容器中
@Component("localeResolver")
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
Locale locale = Locale.getDefault();
String l = httpServletRequest.getParameter("l");
if (!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
注意:该bean的id值必须为localeResolver,因为springBoot会在启动时默认寻找一个id为localeResolver的bean,如果没有发现就用默认的 ,下面就是jar包中的部分内容
@Bean
/**
*前提是容器中不存在这个组件,
*所以使用自己的对象就要配置@Bean让这个条件不成立(实现LocaleResolver 即可)
*/
@ConditionalOnMissingBean
/**
* 如果在application.properties中有配置国际化就用配置文件的
* 没有配置就用AcceptHeaderLocaleResolver 默认request中获取
*/
@ConditionalOnProperty(
prefix = "spring.mvc",
name = {"locale"}
)
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
} else {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
}