SpringBoot实现国际化
1.用idea创建一个springboot的web项目
2.在资源目录中创建一个包:i18n
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f8yyWqNP-1639580765307)(https://img-blog.csdnimg.cn/cdc7e640486f461b904ddf0599ad8407.png?x-osss -process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAUQ2Jb70FF1FF1BAUQ2J050000000000000000000002 )]
3.在i18n中创建一个login.properties文件,添加自己想用的数据,如下:

该文件是网页默认的语言
4.还是在i18n中创建另一个文件:login_zh_CN.properties,添加自己的数据。此时,i18n的目录结构会自动改变

5.同样的创建英文的文件:login_en_US.properties

6.配置application.yml文件

7.创建html页面,放到templates包下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<form action="" method="post">
<label th:text="#{login.username}">Username</label>
<input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}">
<label th:text="#{login.password}">Password</label>
<input type="password" name="password" placeholder="Password" th:placeholder="#{login.password}">
<br> <br>
<div>
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remmber}]]
</label>
</div>
<br>
<button type="submit" th:text="#{login.sign}">Sign in</button>
<br> <br>
</form>
</body>
</html>
8.写一个请求,返回改页面
@Controller
public class HelloController {
@RequestMapping("login")
public String login(){
return "login";
}
}
页面示例

国际化切换实现
1.创建一个config包,创建一个配置类
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login.html").setViewName("login");
}
@Bean
public LocaleResolver localeResolver(){
return new NativeLocaleResolver();
}
protected static class NativeLocaleResolver implements LocaleResolver{
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
}
2.修改页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<form action="" method="post">
<label th:text="#{login.username}">Username</label>
<input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}">
<label th:text="#{login.password}">Password</label>
<input type="password" name="password" placeholder="Password" th:placeholder="#{login.password}">
<br> <br>
<div>
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remmber}]]
</label>
</div>
<br>
<button type="submit" th:text="#{login.sign}">Sign in</button>
<br> <br>
<a th:href="@{/login.html(language='zh_CN')}">中文</a>
<a th:href="@{/login.html(language='en_US')}">English</a>
</form>
</body>
</html>
3.演示示例
 
|