Spring Boot Internationalization i18n

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 工程中,要实现鼠标移上去显示 i18n 国际化的内容,可以采用以下步骤: 1. 在 Spring Boot 工程中添加支持 i18n 的相关依赖,如 `spring-boot-starter-validation` 和 `spring-boot-starter-internationalization`。 2. 在 `application.properties` 或 `application.yml` 中配置 i18n 相关配置,如语言列表和资源文件位置等信息。 3. 在需要显示多语言文本的地方,使用 `MessageSource` 来获取对应语言的文本。 4. 使用 Thymeleaf 模板引擎来渲染页面,并在页面中使用 Thymeleaf 提供的 `th:attr` 属性和 `data-*` 属性来实现鼠标移入显示多语言文本的效果。 示例代码如下: 1. 配置文件 ```yaml spring: messages: basename: i18n/messages ``` 2. 控制器 ```java @Controller public class MyController { @Autowired private MessageSource messageSource; @GetMapping("/") public String index(Model model, Locale locale) { String hello = messageSource.getMessage("hello", null, locale); String world = messageSource.getMessage("world", null, locale); model.addAttribute("hello", hello); model.addAttribute("world", world); return "index"; } } ``` 3. 页面 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Page</title> <style> .tooltip { position: absolute; display: none; border: 1px solid #ccc; background-color: #fff; padding: 5px; } </style> </head> <body> <h1 th:text="${hello}"></h1> <p th:text="${world}" th:attr="data-i18n='world'"></p> <script> function showTooltip(event) { var lang = thymeleafFragmentParameters.locale; var key = event.target.getAttribute('data-i18n'); var text = /* 使用ajax异步获取对应的文本 */; var tooltip = document.createElement('div'); tooltip.className = 'tooltip'; tooltip.textContent = text; document.body.appendChild(tooltip); var x = event.pageX; var y = event.pageY; tooltip.style.left = x + 'px'; tooltip.style.top = y + 'px'; event.target.addEventListener('mouseleave', function() { document.body.removeChild(tooltip); }); } var elements = document.querySelectorAll('[data-i18n]'); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('mouseenter', showTooltip); } </script> </body> </html> ``` 在上面的示例代码中,我们在 `application.yml` 中配置了 i18n 相关配置,使用 `MessageSource` 来获取对应语言的文本,使用 Thymeleaf 模板引擎来渲染页面,并在页面中使用 Thymeleaf 提供的 `th:attr` 属性和 `data-*` 属性来实现鼠标移入显示多语言文本的效果。同时,我们使用了 JavaScript 代码来异步获取多语言文本,并在页面上添加对应的提示框。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值