SpringBoot项目国际化
1、在Resources下创建i18n,在里面创建login.properties,login_zh_CN.properties,login_en_US.properties,
2、点击login_zh_CN.properties,在IDEA界面左下角有Resource Bundle,点击,出现视图
3、在login中,点击“+”号,就可以添加自己想要的属性值
4、在config中创建MyLocaleResolver
package com.li.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
// 获取请求中的语言参数
String language = request.getParameter("l");
Locale locale = Locale.getDefault();//如果没有使用默认的
// 如果链接携带了国际化参数
if (!StringUtils.isEmpty(language)) {
//zh_CN
String[] split = language.split("_");
//国家地区
locale=new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
5、在MyMvcConfig中注册Bean
/ 自定义的国际化组件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
6、在html中添加两个按钮
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" th:href="@{css/login.css}"/>
</head>
<body>
<div>
<div class="bgDiv">
<form th:action="@{/a}">
<div class="login">
<!-- <img th:src="@{/images/login_logo.png}"/>-->
<img class="logoImg" th:src="@{/images/login_logo.png}"/>
<!-- 如果msg不等于空-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<div class="username">
<img class="userImg" style="width: 20px;height: 20px" th:src="@{/images/username.png}"/>
<input class="userInp" name="username" type="text" th:placeholder="#{login.username}"/>
</div>
<div class="pwd">
<img class="pwdImg" style="width: 20px;height: 20px" th:src="@{/images/password.png}"/>
<input class="pwdInp" name="password" type="password" th:placeholder="#{login.password}"/>
</div>
<div class="forgetPwd">
<img class="pwdImg" style="width: 20px;height: 20px" th:src="@{/images/forget.png}"/>
<a class="forgetLink" href="#">[[#{login.remember}]]</a>
</div>
<button class="btn" type="submit">[[#{login.btn}]]</button>
<div>
<a class="btn_a" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn_a" th:href="@{/login.html(l='en_US')}">English</a>
</div>
</div>
</form>
</div>
</div>
</body>
</html>