SpringBoot2.0(十二):SpringBoot2.0国际化
国际化是指将页面显示的信息翻译成不同语言,可以根据不同语言开发多个版本,然后根据用户选择的语言显示不同的页面。其实就是利用浏览器语言里面的中英文切换,将页面的文字转化为相应的中英文。
1. 新建一个“i18n”的包,用来存放国际化配置,然后在这个包下,我们创建一个默认的语言配置、中文语言配置、英文语言配置。
文件名以下划线组合:文件名_区域_语言.properties;当我们这样命名生成文件后,IDEA也会帮我们识别这是个国际化配置。
2. 直接在包右键new就可以了。
点击 + 号输入“en_US”,idea会给我们在创建一个英文配置
3. 点击"login_en_CN.properties"然后切换Resource Bundle的按钮。
4. 为了让配置生效需要在application.properties中添加配置参数。
spring.messages.basename=i18n.login
5. 前端页面使用国际化。
使用th标签之前需要在页面加上xmlns,加上这个之后会有提示!
<html lang="en" xmlns:th="http://www.thymeleaf.org">
然后切换浏览器上面的语言然后刷新页面就会变化了。
注意,我这里将访问的页面其实是;localhost:8080/index.html?l=zh_CN,这也是我们点击中文按钮以后生成的链接。在Thymeleaf的模板语法中,参数是不用“?”的,而是使用小括号,然后参数按照key=value的形式设置,注意单引号;
为了让自定义的配置生效,我们要做的就是覆盖或改变默认的配置,那么我们新建一个文件 MyLocaleResolver,用来实现 LocaleResolver 接口的作用;
import org.springframework.lang.Nullable; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * 国际化配置 * @author xiaofei */ public class MyLocaleResolver implements LocaleResolver{ /** * 解析区域信息 * * @param req * @return */ @Override public Locale resolveLocale(HttpServletRequest req) { // 获取l后面的参数 String l = req.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 httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) { } }
我们的配置生效,当然就要把配置加入到SpringBoot的容器中,所以,在之前的配置文件中,加入Bean:
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.WebMvcConfigurer; /** * 配置 * @author xiaofei */ @Configuration public class MyMvcConfig implements WebMvcConfigurer{ @Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); } }
测试:
代码下载地址:
下载:https://www.lanzous.com/i4jlr1c 密码:i73u
- SpringBoot 2.0 学习(十二)集成MongoDB
- springboot2.0+,整合security配置security关闭http基本验证
- 【官方文档】Spring Boot 2.0 迁移指南 【已翻译54%】
- Spring Boot 2.0(五):Docker Compose + Spring Boot + Nginx + Mysql 实践
- 阿里P9告诉你 Spring Boot 2.0正式发布,升还是不升呢?
- Spring Boot 2.0正式发布,升还是不升呢?
- SpringBoot2.0 整合 tk.mybatis异常
- springboot 2.0 spring boot admin 配置1
- Springboot学习笔记之Springboot 2.0特性
- 使用IDEA构建Spring boot2.0+版本+MyBatis(properties文件配置)
- SpringBoot2.0之整合Dubbo
- SpringBoot系列十二、整合模版引擎freemarker
- Spring Boot 2.0(六):使用 Docker 部署 Spring Boot 开源软件云收藏
- springboot2.0+yml 整合多数据源问题
- Spring Boot学习之旅:(十二)模版引擎-Thymeleaf
- Spring Boot 2.0新增的Actuator端点的特性
- Spring Boot2.0系列教程合集、Spring Cloud系列教程合集、Spring Boot常见错误合集、Spring Cloud常见错误合集
- spring boot 2.0以上版本 配置https,并且输入http自动转为https
- 最详细的搭建eureka 注册中心教程 (1)(springboot 2.0 以上版本)
- SpringBoot 2.0 之使用声明式注解简化缓存