本文共 3151 字,大约阅读时间需要 10 分钟。
@ConfigurationProperties(prefix = "spring.messages")public class MessageSourceAutoConfiguration { /** * Comma-separated list of basenames (essentially a fully-qualified classpath * location), each following the ResourceBundle convention with relaxed support for * slash based locations. If it doesn't contain a package qualifier (such as * "org.mypackage"), it will be resolved from the classpath root. */ private String basename = "messages"; //我们的配置文件可以直接放在类路径下叫messages.properties,springboot自动进行配置 @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(this.basename)) { //设置国际化资源文件的基础名(去掉语言国家代码的) messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray( StringUtils.trimAllWhitespace(this.basename))); } if (this.encoding != null) { messageSource.setDefaultEncoding(this.encoding.name()); } messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale); messageSource.setCacheSeconds(this.cacheSeconds); messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat); return messageSource; }
1. 创建国际化语言配置文件(命名规范请看:)
2. application.properties中配置国际化语言配置文件自定义名称(包名.自定义名称)
spring.messages.basename=i18n/index
3.编写properties文件
点击Resource Bundle进入资源绑定 右击创建属性 添加属性并为属性赋国际化语言值 4.使用thymeleaf中的 “ #{属性名} ” 表达式获取国际化语言值注意: 如果拿不到值显示: ??login.tip_zh_CN?? 表示资源路径问题
如果配置了application.properties中的自定义国际化语言路径,就有可能是版本问题 以下是我使用的thymeleaf版本 还有一种就是将:/换成. spring.messages.basename=i18n.index
3.0.11.RELEASE 2.2.2
5.创建区域解析器
/** * 区域信息解析器 * 作用:解析国际化语言 * 执行:每一次请求,LocaleResolver都会保存当前请求的本地化信息 * 创建人: 渣高帆 * 创建时间: 2020/6/13 23:10 * JDK 1.8 */public class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String area = request.getParameter("area"); //获取当前的语言环境 Locale locale = Locale.getDefault(); //如果传递的参数不为空 if(!StringUtils.isEmpty(area)){ //通过下划线分割获取当前语言代码和国家代码信息 String[] split = area.split("_"); locale = new Locale(split[0],split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { }}
6.编写配置文件
/** * 创建人: 渣高帆 * 创建时间: 2020/6/13 11:03 * JDK 1.8 * 作用:配置类 * * @Configuration标识这是一个配置类,SpringBoot进行自动配置 */@Configurationpublic class MyMvcConfig implements WebMvcConfigurer { /* * 静态页面跳转器 * 只能走静态页面 */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); } /** * 作用:将区域解析器交给Spring托管 * @return 返回区域解析器 */ @Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); }}
7.这里是使用href的形式进行切换(ajax目前还没试用)
每次请求都会去走一遍区域解析器,区域解析器通过传递的参数更改页面展示内容转载地址:http://amqzi.baihongyu.com/