SpringBoot学习笔记(五)SpringBoot进行Web开发-多语支持国际化
多语国际化在SpringMVC中的使用
- 编写国际化配置文件。
- 使用ResourceBundleMessageSource管理国际化资源文件。
- 在JSP页面中可以使用
fmt:message取出国际化的内容。
SpringBoot中的多语国际化
- 编写国际化配置文件,抽取页面需要显示的国际化消息
- SpringBoot自動配置好了管理國際化資源的組件
国际化原理
- local区域信息对象
- LocalResolver获取区域信息对象
- 这是SpringBoot中自动配置默认的区域信息解析器。根据前端请求头中的
Accept-Language:来响应国际化

示例:
- 编写国际化语言参照配置文件

- 在
application.properties中写上spring.messages.basename=i18n.genner - 测试运行,当更改浏览器默认语言时,页面的语言会跟随其修改
- 问题:我需要根据我的前端页面按钮来让用户修改语言
- 编写前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="icon" href="favicon.ico">
</head>
<body>
<h1>TEMPLATES HELLO WORLD</h1>
<h1 th:text="#{genner.hello}"></h1>
<h1 th:text="#{genner.welcome}"></h1>
<a th:href="@{index.html(l='zh_CN')}" th:text="#{genner.language.simple}">中文简体</a>
<a th:href="@{index.html(l='zh_Tr')}" th:text="#{genner.language.tradition}">中文繁体</a>
<a th:href="@{index.html(l='en_US')}" th:text="#{genner.language.english}">英文</a>
</body>
<script src="/jquery.js" th:src="@{/webjars/jquery.3.5.1/jquery.js}"></script>
</html>
- 编写区域信息解析器
package com.hx.component;
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 MylocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] temp = l.split("_");
String language = temp[0];
String country = temp[1];
locale = new Locale(language,country);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
- 编写MyMvcConfig将MylocaleResolver交给容器管理
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送/hx请求,请求到hi.html页面
registry.addViewController("/hx").setViewName("hi");
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
@Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
}
本文来自博客园,作者:Huathy,遵循 CC 4.0 BY-NC-SA 版权协议。转载请注明原文链接:https://www.cnblogs.com/huathy/p/17253853.html

浙公网安备 33010602011771号