Spring Boot 实现国际化步骤:
准备好国际化文件,至少三份(系统默认,中文,英文)
在Spring Boot全局配置文件中,指定国际化文件路径,
自定义Locale Resolver
在页面上使用消息表达式输出国际化内容
案例准备
5. 在resources/templates下新建login.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div id="nav">
<h2>Login Pageh2>
div>
<div>
<form action="" method="post">
<span>usernamespan>:<input type="text" name="username"/><br/>
<span>passwordspan>:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
form>
div>
body>
html>
@Controller
public class IndexController {
@RequestMapping({"/","login.html"})
public String index(){
return "login";
}
}
下面完成国际化
在resources下新建一个文件夹Directory命名为international
在其中新建三个配置文件
login.pwd=pwd
login.tip=登录Page
login.username=账号
login.pwd=password
login.tip=Login Page
login.username=username
login.pwd=密码
login.tip=登录界面
login.username=用户
spring.messages.basename=international.login
原理:国际化locale(区域信息对象) localeResolver(获取区域信息对象)
源码:
默认的就是根据请求头带来的区域信息获取区域信息后去locale进行国际化
浏览器区域信息:
自定义Locale Resolver
/**
* 可以在链接上获取区域信息
*/
public class MylocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String localeLa=request.getParameter("1");
Locale locale=Locale.getDefault();
if(!StringUtils.isEmpty(localeLa)){
String[] s = localeLa.split("_");
locale=new Locale(s[0],s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
**在MyMvcConfig中配置自定义Locale Resolver**
```java
@Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div id="nav">
<h2 th:text="#{login.tip}">Login Pageh2>
div>
<div>
<form action="" method="post">
<span th:text="#{login.username}">usernamespan>:<input type="text" name="username"/><br/>
<span th:text="#{login.pwd}">passwordspan>:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
form>
div>
<div>
<a th:href="@{/login.html(1='zh_CN')}">中文a>/
<a th:href="@{/login.html(1='en_US')}">Englisha>/
div>
body>
html>
新建index.html
给导航栏提取出来在list.html中展示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div th:fragment="nav">
<h2>假设这是导航栏h2>
div>
<div>
This is the index HTML
div>
body>
html>
list.html:
...
<div th:insert="index::nav">
div>
...
如果index.html与list.html在同一目录下,则可直接使用 index::nav
如果不在同一目录下,则要主要路径问题。
测试即可