【WEEK11】 【DAY1】Employee Management System Part 2【English Version】

2024.5.6 Monday
Continuing from 【WEEK10】 【DAY2】Employee Management System Part 1【English Version】

Contents

  • 10.3. Page Internationalization
    • 10.3.1. Preparation
    • 10.3.2. Configuration File Writing
      • 10.3.2.1. Create an i18n (abbreviation for internationalization) directory under the resources folder
      • 10.3.2.2. Create the files login.properties and login_zh_CN.properties in the i18n folder
      • 10.3.2.3. Import Configuration Files
      • 10.3.2.4. Add Key-Value Pairs
    • 10.3.3. Configuration File Activation Exploration
    • 10.3.4. Configuring Page Internationalization Values
      • 10.3.4.1. Modify the index.html page
    • 10.3.5. Configuring Internationalization Resolution
      • 10.3.5.1. In Spring, there is an internationalization Locale (regional information object)
      • 10.3.5.2. Go to the webmvc auto-configuration file
      • 10.3.5.3. Modify the index.html
      • 10.3.5.4. Create MyLocaleResolver.java
      • 10.3.5.5. Modify MyMvcConfig.java
      • 10.3.5.6. Restart and Refresh
    • 10.3.6. Summary

10.3. Page Internationalization

Sometimes, our website will involve switching between Chinese and English or even multiple languages. That’s when we need to learn about internationalization!

10.3.1. Preparation

First, set the encoding for properties files to UTF-8 in IDEA! (File | Settings | Editor | File Encodings)
Change them all to UTF-8
Insert image description here
Write the internationalization configuration file to extract the internationalized page messages that need to be displayed on the page. We can go to the login page to see what content we need to write internationalization configurations for!

10.3.2. Configuration File Writing

10.3.2.1. Create an i18n (abbreviation for internationalization) directory under the resources folder

To store internationalization configuration files

10.3.2.2. Create the files login.properties and login_zh_CN.properties in the i18n folder

IDEA will automatically recognize and generate the new folder
Insert image description here

*If these two files are not automatically merged: you need to download the Resource Bundle Editor plugin
Insert image description here
Insert image description here

10.3.2.3. Import Configuration Files

Insert image description here
Insert image description here
Insert image description here
Insert image description here
Find that login_en_US.properties was generated
Insert image description here

10.3.2.4. Add Key-Value Pairs

Click Resource Bundle to enter a visual interface
Insert image description here
Insert image description here

Similarly
Insert image description here

Finally, five sets of values were added, and the corresponding files will automatically generate code:
login.properties

login.button=Login
login.password=Password
login.remember=Remember Me
login.tip=Please Login
login.username=Username

login_en_US.properties

login.button=Sign in
login.password=Password
login.remember=Remember me
login.tip=Please sign in
login.username=Username

login_zh_CN.properties

login.button=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名

Insert image description here

10.3.3. Configuration File Activation Exploration

Let’s take a look at SpringBoot’s autoconfiguration for internationalization! Here it involves a class: MessageSourceAutoConfiguration.java
There is a method inside, and here we find that SpringBoot has already automatically configured a component to manage our internationalization resource files, ResourceBundleMessageSource

@Bean
@ConfigurationProperties(prefix = "spring.messages")
public MessageSourceProperties messageSourceProperties() {return new MessageSourceProperties();
}// Get the values passed from properties to make judgments
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();if (StringUtils.hasText(properties.getBasename())) {
// Set the base name of the internationalization file (excluding the language and country code)messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));}if (properties.getEncoding() != null) {messageSource.setDefaultEncoding(properties.getEncoding().name());}messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());Duration cacheDuration = properties.getCacheDuration();if (cacheDuration != null) {messageSource.setCacheMillis(cacheDuration.toMillis());}messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());return messageSource;
}

As the actual configuration is placed in the i18n directory, it is necessary to configure the path for these messages -> modify the application.properties file

spring.application.name=springboot-03-web2
#spring.mvc.favicon.enabled=false this method is already deprecated#Turn off the cache of the template engine
spring.thymeleaf.cache=false#Modify the access URL, at this time to access the homepage, the URL that needs to be entered has changed to: http://localhost:8080/111/
#server.servlet.context-path=/111#Modify the recognition address of basename (from the default MessageSourceProperties file to i18n.login)
spring.messages.basename=i18n.login

10.3.4. Configuring Page Internationalization Values

To retrieve internationalization values on the page, consult the Thymeleaf documentation to find that the message retrieval operation is: #{…}.

10.3.4.1. Modify the index.html page

Lines to be modified: 18~22, 25, 28.

<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">Sign in</button>

After restart, the login page:
Insert image description here

10.3.5. Configuring Internationalization Resolution

Goal: Automatically switch between Chinese and English according to the button

10.3.5.1. In Spring, there is an internationalization Locale (regional information object)

There is a resolver called LocaleResolver (to obtain regional information object)!

10.3.5.2. Go to the webmvc auto-configuration file

Find the default SpringBoot configuration:
Line466, click line473 AcceptHeaderLocaleResolver to jump,

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {// If there is no container, configure it yourself; if there is, use the user's configurationif (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {return new FixedLocaleResolver(this.mvcProperties.getLocale());}// Accept header internationalization breakdownAcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();localeResolver.setDefaultLocale(this.mvcProperties.getLocale());return localeResolver;
}

It can be seen that there is a method on line19

public Locale resolveLocale(HttpServletRequest request) {Locale defaultLocale = this.getDefaultLocale();// The default is to obtain Locale for internationalization based on the regional information brought by the request headerif (defaultLocale != null && request.getHeader("Accept-Language") == null) {return defaultLocale;} else {Locale requestLocale = request.getLocale();List<Locale> supportedLocales = this.getSupportedLocales();if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);if (supportedLocale != null) {return supportedLocale;} else {return defaultLocale != null ? defaultLocale : requestLocale;}} else {return requestLocale;}}
}

-> If we now want to click on a link to make our internationalization resources take effect, we need to make our own Locale take effect -> try to overwrite it.

10.3.5.3. Modify the index.html

Lines 30, 31

<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>

10.3.5.4. Create MyLocaleResolver.java

Insert image description here

package com.P14.config;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;public class MyLocaleResolver implements LocaleResolver {// Resolve the request@Overridepublic Locale resolveLocale(HttpServletRequest request) {// Get the language parameter from the requestString language = request.getParameter("l");// Use the default if no custom one is definedLocale locale = Locale.getDefault();// If the request link carries internationalization parametersif (!StringUtils.isEmpty(language)){// Split the request parametersString[] split = language.split("_");// Country, regionlocale = new Locale(split[0],split[1]);}return locale;}@Overridepublic void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {}
}

10.3.5.5. Modify MyMvcConfig.java

package com.P14.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;@Configuration
//@EnableWebMvc   // This imports a class, DelegatingWebMvcConfiguration, which acquires all the webMvcConfig from the container
public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {// Redirect the following two URLs to the index page fileregistry.addViewController("/").setViewName("index");registry.addViewController("/index.html").setViewName("index");}// Make the custom internationalization component effective@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}
}

10.3.5.6. Restart and Refresh

Chinese:
Insert image description here

English:
Insert image description here

10.3.6. Summary

  1. Homepage configuration:
    • Note that all pages’ static resources need to be managed by Thymeleaf
    • URL: @{}
  2. Page Internationalization
    • We need to configure i18n files
    • If we want to automatically switch buttons in the project, we need to define a component LocaleResolver
    • Remember to configure the components you write into the Spring container with @Bean
    • #{}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/3018692.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

(超简单)SpringBoot中简单用工厂模式来实现

简单讲述业务需求 业务需要根据不同的类型返回不同的用户列表&#xff0c;比如按角色查询用户列表、按机构查询用户列表&#xff0c;用户信息需要从数据库中查询&#xff0c;因为不同的类型查询的逻辑不相同&#xff0c;因此简单用工厂模式来设计一下&#xff1b; 首先新建一个…

【C++历练之路】红黑树——map与set的封装实现

W...Y的个人主页&#x1f495; gitee代码仓库分享&#x1f60a; 前言&#xff1a;上篇博客中&#xff0c;我们为了使二叉搜索树不会出现”一边倒“的情况&#xff0c;使用了AVL树对搜索树进行了处理&#xff0c;从而解决了数据在有序或者接近有序时出现的情况。但是AVL树还会…

创建Chrome插件:自动刷新网页

创建Chrome插件&#xff1a;自动刷新网页 前言 在日常工作和生活中&#xff0c;我们经常需要频繁刷新网页以获取最新的数据和信息。无论是开发人员进行网站测试&#xff0c;还是用户关注实时股市动态&#xff0c;手动刷新网页既耗时又低效。因此&#xff0c;本文将介绍如何创…

LeetCode--所有质数、质数对

1.0 Q: 输出 100 以内所有质数 1.1 /* 第一层循环控制检查到哪个数* 第二层通过遍历除以每个比他小的数的方式,检查每个数是不是质数* 由于要遍历检查,设置一个标记,只要任意一次循环可以整除,我们就设置该标记为不是质数 */boolean isPrime true;for (int i 2; i < 100…

RDB快照是怎么实现的?

RDB快照是怎么实现的&#xff1f; 前言快照怎么用&#xff1f;执行快照时&#xff0c;数据能被修改吗&#xff1f;RDB 和 AOF 合体 前言 虽说 Redis 是内存数据库&#xff0c;但是它为数据的持久化提供了两个技术。 分别是「 AOF 日志和 RDB 快照」。 这两种技术都会用各用一…

鸿蒙OpenHarmony南向:【Hi3516标准系统入门(IDE方式)】

Hi3516标准系统入门&#xff08;IDE方式&#xff09; 注意&#xff1a; 从3.2版本起&#xff0c;标准系统不再针对Hi3516DV300进行适配验证&#xff0c;建议您使用RK3568进行标准系统的设备开发。 如您仍然需要使用Hi3516DV300进行标准系统相关开发操作&#xff0c;则可能会出现…

【排序算法】之快速排序

一、算法介绍 快速排序(Quick sort)是由C.A.R.Hoare提出来的。快速排序法又叫分割交换排序法&#xff0c;是目前公认的最佳排序法&#xff0c;也是使用“分而治之”的方式&#xff0c;会先在数据中找到一个虚拟的中间值&#xff0c;并按此中间值将所有打算排序的数据分为两部分…

未来娱乐新地标?气膜球幕影院的多维体验—轻空间

在中国&#xff0c;一座独特的娱乐场所正在崭露头角&#xff1a;气膜球幕影院。这个融合了气膜建筑与激光投影技术的创新场所&#xff0c;不仅令人惊叹&#xff0c;更带来了前所未有的科幻娱乐体验。让我们一起探索这个未来的娱乐空间&#xff0c;感受其中的多维魅力。 现场演出…

java语言数据结构(单链表)

前言 不得承认java应用的广泛&#xff0c;所以毅然决定java版本的数据结构和算法专题还是要坚决更新。每日更新2题&#xff0c;希望学习的小伙伴可以关注一波跟上&#xff0c;评论区欢迎讨论交流。 实现原理 节点&#xff08;Node&#xff09;&#xff1a;链表的基本构建单元…

微信小程序(Taro)获取经纬度并转化为具体城市

1、获取经纬度 申请权限&#xff0c;想要使用微信小程序获取经纬度的方法是要申请该方面的权限。 获取经纬度的方法有很多选择其中一个使用就好。 我使用的是Taro.getFuzzyLocation(&#xff09; 在app.config.js中需要添加设置 requiredPrivateInfos: ["getFuzzyLocat…

Raft共识算法图二解释

下面是有关Raft协议中不同术语和概念的翻译及解释&#xff1a; 术语和概念&#xff1a; 任期号&#xff08;term number&#xff09;&#xff1a;用来区分不同的leader。前一个日志槽位的信息&#xff08;prelogIndex&#xff09;&#xff1a;这是前一个日志条目的索引&#…

集成逻辑分析器( ILA)IP核用法详解

集成逻辑分析器&#xff08;Integrated Logic Analyzer, ILA&#xff09;IP核是一个可定制的逻辑分析器&#xff0c;用于监测设计的内部信号。ILA核心包含了现代逻辑分析器的许多高级特性&#xff0c;比如布尔触发方程&#xff08;boolean trigger equations&#xff09;和边沿…

H5视频付费点播打赏影视系统程序全开源运营版

这是一款视频打赏源码&#xff0c;勿做非法用途&#xff0c;由用户亲测功能完善&#xff0c;源码仅用于学习使用&#xff0c;分享链接是用户云盘&#xff0c;具有时效性&#xff0c;感兴趣的可以去学习。 thinkphp开发&#xff0c;前后端分离设计&#xff0c;支持游客登陆、VIP…

了解集合与数据结构(java)

什么是数据结构? 数据结构就是 数据结构, 功能就是描述和组织数据 比如我有10万个QQ号, 我来组织, 有很多种组织方法, 比如链表, 树, 堆, 栈等等. 假如QQ号要查找数据, 有种数据结构查找数据速度很快, 我们就用它 加入QQ号要进行删除数据, 有种数据结构删除速度很快, 我们…

Python中设计注册登录代码

import hashlib import json import os import sys # user interface 用户是界面 UI """ 用户登录系统 1.注册 2.登陆 0.退出 """ # 读取users.bin def load(path): return json.load(open(path, "rt")) # 保存user.bin def save(dic…

Covalent引入五个新网络运营商,提升去中心化特性和数据安全性

为了进一步扩大运营商基础以并践行去中心化网络基础设施的宗旨&#xff0c;Covalent Network&#xff08;CQT&#xff09;在网络中引入了五个新的区块样本生产者&#xff08;BSPs&#xff09;角色。该举措不仅重申了 Covalent Network&#xff08;CQT&#xff09;对社区驱动协议…

如何保护数据安全?迅软DSE加密系统给信息撑把保护伞!

信息安全当然需要保护&#xff0c;不然企业的信息可以发给任何人&#xff0c;普通信息还好&#xff0c;如果是重要机密呢&#xff0c;企业重要信息被发出去后可能会造成一些麻烦&#xff0c;所以可以使用加密系统&#xff0c;对数据进行安全保护&#xff0c;防止泄密问题&#…

pandas 预处理

文章目录 第1关&#xff1a;数据读取与合并第2关&#xff1a;数据清洗第3关&#xff1a;数据转换 第1关&#xff1a;数据读取与合并 任务描述 本关任务&#xff1a;加载 csv 数据集&#xff0c;实现 DataFrame 合并。 知识讲解 Pandas 模块导入 import pandas as pd 读取 cs…

如何在没有备份的情况下恢复 Mac 上丢失的数据

如果您因意外删除、错误格式化硬盘或文件损坏而丢失了重要的、感伤的文件、照片或音乐&#xff0c;那么这可能会令人非常痛苦。幸运的是&#xff0c;您有几个选择。 您的 Mac 位于数字宇宙的中心。您可能会在上面留下照片和视频形式的记忆&#xff0c;以及来自您不再见面的朋友…

[嵌入式系统-69]:RT-Thread-组件:网络组件“组”,RT-Thread系统通向外部网络世界的入口

目录 RT-Thread 提供的网络世界入口 - 网络组件 1. 总概 2. AT 3. Lwip&#xff1a; 轻量级IP协议栈 4. W5500 5. Netdev 6. RT-Thread SAL&#xff08;Socket Abstraction Layer&#xff09;套接字和BSD套接字区别 RT-Thread SAL 套接字接口示例 BSD 套接字接口示例 …