第一步:导入spring Web和thymeleaf依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
第二步:在resources目录中新建名为 i18n 的包,在里面新建三个properties文件。
a.properties:
a.btn=登录
a.password=密码
a.username=用户名
a_zh_CN.properties:
a.btn=登录
a.password=密码
a.username=用户名
a_en_US.properties:
a.btn=login
a.password=Password
a.username=Username
注意:其中a_zh_CN.properties文件和a_en_US.properties:文件中间的名字要必须使用这个(zh_CN和en_US),其他随意。
第三步:在application.properties文件中加入代码:
spring.messages.basename=i18n.a
第四步:新建html文件。
<!DOCTYPE html>
<html lang="en" xmlns:th="www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" name="username" th:placeholder="#{a.username}">
<input type="password" name="password" th:placeholder="#{a.password}">
<a class="btn btn-sm" th:href="@{/text(s='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/text(s='en_US')}">English</a>
<button type="submit" th:value="#{a.btn}"></button>
</body>
</html>
第五步:新建一个三个接口文件。
a:
注意:一定要导入 import org.springframework.util.StringUtils 这个包。
package com.example.v;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class a implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String v = request.getParameter("s");
Locale locale= Locale.getDefault();
if (!StringUtils.isEmpty(v)){
String[]s= v.split("_");
locale =new Locale(s[0],s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
b:
package com.example.v;
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.WebMvcConfigurer;
@Configuration
public class b implements WebMvcConfigurer {
@Bean
LocaleResolver localeResolver(){
return new a();
}
}
text:
package com.example.v;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class text {
@RequestMapping("/text")
public String a(){
return "text";
}
}