springboot web开发

国际化配置

在yml中:

1
2
3
spring:
messages:
basename: i18n/index

resources下新建文件夹i18n,再i18n下新建三个文件:index.propertiesindex_zh_CN.propertiesindex_en_US.properties,分别表示默认文字,中文,英文;如下为中文的示例

1
2
3
4
index.welcome=欢迎!
index.user=用户
index.Chinese=中文
index.English=英文

templates下新建thymeleaf模板的index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="#{index.welcome}"></h1>
<h2 th:text="#{index.user}"></h2>
<a th:href="@{/index(language='zh_CN')}" th:text="#{index.Chinese}"></a>
<a th:href="@{/index(language='en_US')}" th:text="#{index.English}"></a>
</body>
</html>

新建配置类MyMvcConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
return new NativeLocalResolver();
}
protected static class NativeLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language");
System.out.println("-----"+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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
}

控制器里的路由函数跳转到index或者直接访问服务域名端口

多数据源切换

您的支持鼓励我继续创作!