一、idea创建spring boot,Thymeleaf 项目
二、在resources下创建一个文件夹(i18n)
1.在新创建的文件夹下创建login.properties文件。
按要求创建login_en_US.properties (en_US 国家名称缩写 固定)
在创建文件下点击Resource Bundile 插入字段
2.配置文件yml
三、导入需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
四、创建一个类实现LocaleResolver接口
package com.qf.i18ndemo;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* 编码:
* 日期:{2023/4/13}
* 描述:
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");//获取前端发过来的l
Locale locale = Locale.getDefault();//获得默认的语言环境对象
if (l!= null&&!"".equals(l)) {
locale = new Locale(l.split("_")[0],l.split("_")[1]);
//@{/login.html(l='zh_CN')}分割zh_CN
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
五、创建一个类实现WebMvcConfigurer接口
package com.qf.i18ndemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 编码:
* 日期:{2023/4/13}
* 描述:
*/
@Configuration//声明配置类
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
}
@Bean//放入ioc容器中
public LocaleResolver localeResolver() {//将自定义的 语言解析器对象注册在ioc容器当中
//方法名必须叫localeResolver
//springboot语言解析器根据名字找
return new MyLocaleResolver();
}
}
六、前端调用
注意引入<html xmlns:th="http://www.thymeleaf.org" >
<div class="dowebok" id="dowebok">
<div class="form-container sign-in-container">
<form action="#">
<h1 th:text="#{tip}">登录</h1>
<input type="text" th:placeholder="#{username}">
<input type="password" th:placeholder="#{password}">
<a href="#" th:text="#{forgetPwd}">忘记密码?</a>
<button th:text="#{btn}">登录</button>
<a th:href="@{/login.html(l='zh_CN')}">中文</a>
<a th:href="@{/login.html(l='en_US')}">English</a>
<a th:href="@{/login.html(l='ja_JP')}">日文</a>
</form>
</div>