SpringBoot Web开发(5) 开发页面国际化+登录拦截
一、页面国际化
页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换。
**效果演示:**当浏览器语言设置为英文优先时,或者用户点击页面“English”选项时,页面如下图所示:
当浏览器语言设置为中文优先时,或者用户点击页面“中文”选项时,页面如下图所示:
下面说说具体的实现步骤及实现原理:
一、编写国际化配置文件,抽取页面需要显示的国际化消息
在resources资源文件夹下创建“i18n”国际化文件夹,在其中编写国际化配置文件。
二、SpringBoot自动配置好了管理国际化资源文件的组件,部分源码如下:
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = new Resource[0];
public MessageSourceAutoConfiguration() {
}
@Bean
@ConfigurationProperties(
prefix = "spring.messages"
)
.....
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
}
三、在application.properties中配置国际化文件夹的路径
spring.messages.basename=i18n.login
四、在页面上获取国际化的值
<!DOCTYPE html>
<!--引入Thymeleaf模板名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link href="favicon.ico" rel="shortcut icon">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content=""