目录
Locale:区域信息对象
LocaleResolver:获取区域信息对象
SpringBoot国际化
步骤:
1、需要有进行国际化的html文件
2、编写国际化配置文件
3、html中取国际化配置文件的值
4、application.properties中开启国际化
实现:
1、需要有进行国际化的html文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>国际化测试</title>
</head>
<body>
<h3>中文</h3>
<hr />
</body>
</html>
2、编写国际化配置文件
在resource包下,创建i18n包,建立三个文件
index.properties(默认)
#默认显示
value=中文
index_zh_CN.properties(中文)
#中文
value=中文
index_en_US.properties(英文)
#英文
value=englist
3、html中取国际化配置文件的值
4、application.properties中开启国际化
spring.messages.basename=i18n.index
测试:
默认效果
切换英文,选择United States放在首位,刷新链接
IDEA比eclipse方便很多(我用的是IDEA开发,eclipse练习)
添加链接切换国际化
步骤:
前面的编写国际化配置文件和在application.properties开启国际化两步不能少
1、html文件加链接
2、编写自己MyLocaleResolver,实现LocaleResolver,从链接中获取区域信息,并设置到Locale中
3、注册自己的LocaleResolver组件
实现:
1、html文件加链接
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>国际化测试</title>
</head>
<body>
<h3 th:text="#{value}">中文</h3>
<p></p>
<a th:href="@{/index.html(l='zh_CN')}">中文</a>
<a th:href="@{/index.html(l='en_US')}">English</a>
<hr />
</body>
</html>
2、编写自己MyLocaleResolver,实现LocaleResolver,从链接中获取区域信息,并设置到Locale中
package com.test.component;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
/**
* 国际化链接处理文件
* @author xuexue
*
*/
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[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
// TODO Auto-generated method stub
}
}
3、注册自己的LocaleResolver组件
package com.test.config;
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.WebMvcConfigurerAdapter;
import com.test.component.MyLocaleResolver;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//跳转到主页
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
/**
* 注册自己的国际化组件
* @return
*/
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
}
测试:
点击英文