1.编写相关配置文件(注意命名xxx_zh_CN,xxx_zh_TW)
springboot配置文件
spring.messages.basename=i18n/login
2.增加一个配置类MainConfig,实现WebMvcConfigurer
addInterceptors方法中增加了一个国际化拦截器,
会拦截前端_lang参数,
因为localeResolver方法中实例化了CookieLocaleResolver对象,
所以language参数会存在cookie中,
所有的页面都可以从cookie中取到language参数。
你也可以使用SessionLocaleResolver将参数存到session。
@Configuration
public class MainConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver slr = new CookieLocaleResolver();
// 默认语言,中文
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 参数名
lci.setParamName("language");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
3.前端代码部分
<!DOCTYPE html>
<html lang="en">
<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 Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" rel="stylesheet">
<script src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script>
$(function () {
$("#ch").click(function () {
window.location.href = "index?language=zh_CN";
})
$("#en").click(function () {
window.location.href = "index?language=en_US";
})
})
</script>
//
<#import "spring.ftl" as spring />
</head>
<body class="text-center">
<form class="form-signin" action="/dashboard">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal"><@spring.message "login.tip"/></h1>
<label class="sr-only">Username</label>
<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> <@spring.message "login.remenber"/>
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" id="ch">中文</a>
<a class="btn btn-sm" id="en">English</a>
</form>
</body>
</html>