15 | SpringBoot + thymeleaf 的登陆页面如何实现国际化

1、编写国际化配置文件,抽取页面需要显示的国际化消息

(1)在resources文件夹下创建i18n文件夹,用来存放国际化配置文件,为什么是i18n???

i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。
15 | SpringBoot + thymeleaf 的登陆页面如何实现国际化_第1张图片

然后任意打开一个配置文件,如login_en_US.properties,点击Resources Bundle,输入你想要国际化的属性
15 | SpringBoot + thymeleaf 的登陆页面如何实现国际化_第2张图片

(2)在全局配置文件中绑定这些自定义的国际化配置
SpringBoot自动配置好了管理国际化资源文件的组件

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
    
    /**
	 * Comma-separated list of basenames (essentially a fully-qualified classpath
	 * location), each following the ResourceBundle convention with relaxed support for
	 * slash based locations. If it doesn't contain a package qualifier (such as
	 * "org.mypackage"), it will be resolved from the classpath root.
	 */
	private String basename = "messages";  
    //我们的配置文件可以直接放在类路径下叫messages.properties;
    
    @Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		if (StringUtils.hasText(this.basename)) {
            //设置国际化资源文件的基础名(去掉语言国家代码的)
			messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
					StringUtils.trimAllWhitespace(this.basename)));
		}
		if (this.encoding != null) {
			messageSource.setDefaultEncoding(this.encoding.name());
		}
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
		messageSource.setCacheSeconds(this.cacheSeconds);
		messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
		return messageSource;
	}

我们的配置文件可以直接放在类路径下叫messages.properties 不用做任何配置就可使用国际化,但我们这里创建了一个i18n文件夹,所以我们要在全局配置文件中通过spring.messages.messages绑定资源文件的基础名(去掉语言国家代码的)

application.properties

spring.messages.basename=i18n.login

2、修改login.html

https://www.webjars.org/
公共资源用webjars提供的东西,自己的资源就用assets文件夹里的


        <dependency>
            <groupId>org.webjarsgroupId>
            <artifactId>bootstrapartifactId>
            <version>4.5.0version>
        dependency>

login.html


<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<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="">
	<title>Signin Template for Bootstraptitle>
	
	<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.5.0/css/bootstrap.css}" rel="stylesheet">
	
	<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
head>

<body class="text-center">
<form class="form-signin" action="dashboard.html">
	<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
	<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign inh1>
	<label class="sr-only" th:text="#{login.username}">Usernamelabel>
	<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
	<label class="sr-only" th:text="#{login.password}">Passwordlabel>
	<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
	<div class="checkbox mb-3">
		<label>
			<input type="checkbox" value="remember-me"/> [[#{login.remember}]]
		label>
	div>
	<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign inbutton>
	<p class="mt-5 mb-3 text-muted">© 2017-2018p>
	<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文a>
	<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">Englisha>
form>
body>
html>

3、编写MyLocaleResolver实现LocaleResolver接口

(1)创建MyLocaleResolver类

//可以在连接上携带区域信息
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.getParameter("l");
        // 如果没有 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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

为什么要实现LocaleResolver接口呢??
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);

	        @Bean
		@ConditionalOnMissingBean
		@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
		public LocaleResolver localeResolver() {
			if (this.mvcProperties
					.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
				return new FixedLocaleResolver(this.mvcProperties.getLocale());
			}
			AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
			localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
			return localeResolver;
		}
默认的就是根据请求头带来的区域信息获取Locale进行国际化

(2)在配置类中注册这个Bean

//使用WebMvcConfigurer可以来扩展SpringMVC的功能
//@EnableWebMvc   不要接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //所有的WebMvcConfigurer组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return webMvcConfigurer;
    }
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

ok,到登录页面按中/英文按钮可以切换成中英文页面
15 | SpringBoot + thymeleaf 的登陆页面如何实现国际化_第3张图片
15 | SpringBoot + thymeleaf 的登陆页面如何实现国际化_第4张图片

你可能感兴趣的:(SpringBoot)