SpringBoot整合国际化功能

时间:2023-03-09 21:35:36
SpringBoot整合国际化功能

(1)、编写国际化配置文件

  在resources下新建i18n文件夹,并新建以下文件

  ①index.properties

    username=username

  ②index_en_US.properties

    username=username

  ③index_zh_CN.properties

    username=用户名

(2)、使用ResourceBundleMessageSource管理国际化资源文件

*SpringBoot已经自动配置了管理国际化资源文件的组件

SpringBoot整合国际化功能

(3)在配置文件中指定国际化资源文件的文件夹及基础文件

#指定国际化资源文件的文件夹及基础文件 spring.messages.basename=i18n/index

(4)* 编写自定义的Locale区域解析器

 package cn.coreqi.config;

 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; /**
* SpringBoot默认的Locale解析器是根据请求头的区域信息进行解析的(浏览器语言)
* 使用自定义的Locale解析器对url的区域信息进行解析达到点击切换区域效果
* 一旦我们自定义的区域解析器注册到Spring容器中,则SpringBoot提供的将不自动注册
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.getParameter("l");
if(!StringUtils.isEmpty((l))){
String [] s = l.split("_");
return new Locale(s[0],s[1]);
}
return Locale.getDefault();
} @Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { }
}

(5)注册我们自定义的区域解析器

 package cn.coreqi.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.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /**
* 扩展SpringMVC
* SpringBoot2使用的Spring5,因此将WebMvcConfigurerAdapter改为WebMvcConfigurer
* 使用WebMvcConfigurer扩展SpringMVC好处既保留了SpringBoot的自动配置,又能用到我们自己的配置
*/
//@EnableWebMvc //如果我们需要全面接管SpringBoot中的SpringMVC配置则开启此注解,
//开启后,SpringMVC的自动配置将会失效。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//设置对“/”的请求映射到index
//如果没有数据返回到页面,没有必要用控制器方法对请求进行映射
registry.addViewController("/").setViewName("index");
} //注册我们自定义的区域解析器,一旦将我们的区域解析器注册到Spring容器中则SpingBoot
//默认提供的区域解析器将不会自动注册
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}

(6)视图中引用国际化内容

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Index首页</title>
</head>
<body>
<h1 th:text="#{username}"></h1>
</body>
</html>

(7)测试

SpringBoot整合国际化功能

SpringBoot整合国际化功能