效果如图所示,有一个可以选择英文和中文的下拉框,下面还会介绍一种不用下拉框,而是直接判断操作系统语言,然后显示和操作系统语言对应的文中或者英文页面。
(忽略红色框框,没有任何提示的意思 ,那是我之前截的图)
一、需要配置的地方
1.pom.xml添加thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.application.yml配置文件
spring:
messages:
basename: static/i18n/messages #相对路径 首部请勿添加斜杠
3.创建3个文件,messages.properties可以没有内容,但是文件必须存在,zh_CN里面是中文翻译,en_US里面是英文翻译,当然你可以新建文件夹里面还有别的语言,文件名要符合国际国家名称代码标准。
修改翻译内容后重启服务才会生效,这是thyme leaf的原因
4.配置i18n配置文件 I18nConfig.java和MyIntercepter.java
package com.hqgd.switchgear.common;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.context.i18n.TimeZoneAwareLocaleContext;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.util.Assert;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AbstractLocaleContextResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils;
/***
* i18n配置文件
*
*
*/
@Configuration
@ComponentScan
public class I18nConfig extends AbstractLocaleContextResolver {
public static final String LOCALE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".LOCALE";
public static final String TIME_ZONE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".TIME_ZONE";
@Value("${spring.messages.basename}")
public String[] basefilenames;
@Bean(name = "localeResolver")
public LocaleResolver localeResolverBean() {
String lang = System.getProperty("user.language");//获取操作系统语言
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
/**
/我这里是除了中文操作系统之外,其余全部显示英文,这种情况适用于前端没有下拉框,
根据操作系统语言默认打开相应版本,如果前端有下拉框可以选择,这里就不需要if判断,
直接设置一个默认就好了,或中文或英文自己决定。
String lang = System.getProperty("user.language");这行代码也就不需要了
*/
if (lang == "zh") {
sessionLocaleResolver.setDefaultLocale(Locale.CHINESE);
} else {
sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);
}
return sessionLocaleResolver;
}
/**
* 用于解析消息的策略接口,支持这些消息的参数化和国际化。
*/
@Bean(name = "messageSource")
public ResourceBundleMessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
if (basefilenames != null) {
for (int i = 0; i < basefilenames.length; i++) {
String basename = basefilenames[i];
Assert.hasText(basename, "Basename must not be empty");
this.basefilenames[i] = basename.trim();
}
source.setBasenames(basefilenames);
} else {
this.basefilenames = new String[0];
source.setBasename(basefilenames[0]);
}
source.setDefaultEncoding("UTF-8");
source.setUseCodeAsDefaultMessage(true);
return source;
}
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
this.setLocaleContext(request, response, locale != null ? new SimpleLocaleContext(locale) : null);
}
@Override
public LocaleContext resolveLocaleContext(HttpServletRequest request) {
return null;
}
@Override
public void setLocaleContext(HttpServletRequest request, HttpServletResponse response,
LocaleContext localeContext) {
Locale locale = null;
TimeZone timeZone = null;
if (localeContext != null) {
locale = localeContext.getLocale();
if (localeContext instanceof TimeZoneAwareLocaleContext) {
timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
}
}
WebUtils.setSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME, locale);
WebUtils.setSessionAttribute(request, TIME_ZONE_SESSION_ATTRIBUTE_NAME, timeZone);
}
}
package com.hqgd.switchgear.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
/**
* 国际化工具类
*/
@SuppressWarnings("deprecation")
@Configuration
public class MyIntercepter extends WebMvcConfigurerAdapter {
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");//前端的传参
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
二、前端代码
1.每一个需要翻译的页面的html都要加这句
<html xmlns:th="http://www.thymeleaf.org">
在需要翻译的地方使用th:text的方式代替,翻译必须用“#{}”,里面的内容是你在翻译文件中的值
js代码,这里是下拉框切换的时候需要用的,如果根据系统语言默认就不需要了,ROOT是url路径,也就是打开网站的地址,根据你自己的填写。
<script th:inline="javascript">
var ROOT = "http://localhost:9000/hqgd";
var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];
$("#locale").find('option[value="' + LANG_COUNTRY + '"]').attr(
'selected', true);
$("#locale").change(function() {
$.get(ROOT + '/?lang=' + $("#locale").val(), function() {
location.reload();
});
});
</script>
后端
1.加载页面必须经过后台,每一个页面都要经过后台,否则无法映射,这点很重要!!!!
return后面的值就是你的login.html和register.html所在位置,我的在template下,所以直接返回。
至此就完成了。