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

news2024/12/23 5:24:20

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 configuration
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    // Accept header internationalization breakdown
    AcceptHeaderLocaleResolver 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 header
    if (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
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // Get the language parameter from the request
        String language = request.getParameter("l");
        // Use the default if no custom one is defined
        Locale locale = Locale.getDefault();
        // If the request link carries internationalization parameters
        if (!StringUtils.isEmpty(language)){
            // Split the request parameters
            String[] split = language.split("_");
            // Country, region
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public 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 {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // Redirect the following two URLs to the index page file
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    // Make the custom internationalization component effective
    @Bean
    public 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://www.coloradmin.cn/o/1652090.html

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

相关文章

iframe通信postMessage

iframe嵌入页面是实现微前端的方式之一。由于浏览器的跨域限制&#xff0c;iframe与父页面之间的通信变得不是那么容易。postMessage解决了这个问题。从广义上讲&#xff0c;一个窗口可以获得对另一个窗口的引用&#xff08;比如 targetWindow window.parent&#xff09;&…

增强for循环(for-each循环)

增强for循环&#xff08;for-each循环&#xff09;通常可以用于遍历实现Iterable接口的数据结构。Iterable接口定义了一个iterator()方法&#xff0c;该方法返回一个迭代器对象&#xff0c;用于遍历集合中的元素。 以下是一些常见的实现了Iterable接口的数据结构&#xff0c;可…

【大比武02】建设项目电子档案中的CA电子签名应用

关注我们 - 数字罗塞塔计划 - 应用CA电子签名取代手工签名和盖章是建设项目电子档案中可信存证的关键抓手。国内已有成熟应用的标杆性案例&#xff0c;如大湾区深中通道、广东惠清高速等。 然而&#xff0c;CA电子签名的必要性尚没有得到广泛认同&#xff0c;其应用过程中的问…

Charles抓包工具

Charles是一个HTTP代理工具&#xff0c;使开发人员能够查看客服端和服务器之间的所有HTTP/ HTTPS/SSL网络请求。 Charles是在PC环境下常用的网络抓包截取工具&#xff0c;在做移动开发时&#xff0c;我们为了调试客户端与服务端的网络通讯协议&#xff0c;常常需要截取网络请求…

【千帆平台】使用AppBuilder零代码创建应用,Excel表格数据转为Markdown格式文本

欢迎来到《小5讲堂》 这是《千帆平台》系列文章&#xff0c;每篇文章将以博主理解的角度展开讲解。 温馨提示&#xff1a;博主能力有限&#xff0c;理解水平有限&#xff0c;若有不对之处望指正&#xff01; 目录 前言创建应用应用名称应用描述应用头像角色指令组件能力开场白推…

MouseBoost PRO mac中文激活版:专业鼠标助手

MouseBoost PRO mac鼠标性能优化软件&#xff0c;以其强大的功能和智能化的操作&#xff0c;助您轻松驾驭鼠标&#xff0c;提高工作效率。 MouseBoost PRO支持自定义快捷键设置&#xff0c;让您轻松实现快速切换应用程序、打开特定文件、调节音量大小等操作。自动识别窗口功能则…

【大前端】ECharts 绘制立体柱状图

立体柱状图分为&#xff1a; 纯色立体柱状图渐变立体柱状图 常用实现方式 纯色立体柱状图 纯色立体柱状图&#xff0c;使用MarkPoint和颜色渐变就实现&#xff0c;如下代码 import * as echarts from "echarts";var chartDom document.getElementById("main&…

基于Spring Ai 快速创建一个AI会话

文章目录 1、创建SpringBoot项目2、引入依赖3、修改配置文件4、一个简单的会话 前期准备 在OpenAI 注册页面创建帐户并在API 密钥页面生成令牌。 Spring AI 项目定义了一个配置属性&#xff0c;您应该将其设置为从 openai.com 获取的spring.ai.openai.api-key值 代码托管于gite…

终端安全管理措施有哪些?好用终端安全管理软件推荐(建议收藏)

在当今数字化时代&#xff0c;信息安全已成为企业运营不可或缺的一部分。其中&#xff0c;终端安全为您详细介绍&#xff0c;并推荐几款好用的终端安全管理软件&#xff0c;帮助您更好地保护企业信息安全。管理是确保企业信息安全的重要环节。那么&#xff0c;终端安全管理措施…

厂房环保水空调有多节能环保呢?

环保水空调确实具有显著的节能环保特点。其节能环保的优点主要体现在以下几个方面&#xff1a; 高效节能&#xff1a;环保水空调利用水的热传导和相变特性&#xff0c;通过水泵将冷热水循环运行&#xff0c;实现室内温度的控制。由于水具有较大的热容量&#xff0c;能够高效地…

【经验01】spark执行离线任务的一些坑

项目背景: 目前使用spark跑大体量的数据,效率还是挺高的,机器多,120多台的hadoop集群,还是相当的给力的。数据大概有10T的量。 最近在出月报数据的时候发现有一个任务节点一直跑不过去,已经超过失败次数的阈值,报警了。 预警很让人头疼,不能上班摸鱼了。 经过分析发现…

Java OOM问题排查

1.问题现象 tomcat web页面无法访问&#xff0c;日志报出如下错误&#xff0c; 问题出现频率 1晚上1次。 有时候会打印出oom的代码位置&#xff0c;有时候不会打印&#xff0c;不会打印则按照如下流程排查 2.问题排查过程 排查OOM主要是要获取内存的快照文件&#xff0c;但…

【CTF Web】攻防世界 GFSJ0478 cookie Writeup(HTTP协议+信息收集+Cookie)

cookie X老师告诉小宁他在cookie里放了些东西&#xff0c;小宁疑惑地想&#xff1a;‘这是夹心饼干的意思吗&#xff1f;’ 解法 按 F12&#xff0c;点击网络。 刷新页面。查看请求头中的 Cookie。 look-herecookie.php访问&#xff1a; http://61.147.171.105:53668/cookie.…

SpringBoot过滤器简单构建详细教程以及与拦截器区别解释

作用范围&#xff1a;过滤器基于Servlet规范&#xff0c;作用于更广泛的层面&#xff0c;不仅限于Spring MVC&#xff0c;它可以拦截进入Web应用的所有请求&#xff0c;包括静态资源请求。过滤器可以对请求和响应的内容进行预处理和后处理。实现方式&#xff1a;过滤器需要实现…

森林消防—高扬程水泵,高效、稳定、可靠!/恒峰智慧科技

森林&#xff0c;作为地球的“绿色肺叶”&#xff0c;不仅为我们提供了丰富的自然资源&#xff0c;更是维持生态平衡的重要一环。然而&#xff0c;随着全球气候的变化和人为活动的增加&#xff0c;森林火灾频发&#xff0c;给生态环境和人民生命财产安全带来了巨大威胁。在森林…

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

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

Apple 添加了 13 英寸 iPad Air

劈啪&#xff01;苹果推出的新款 iPad Air&#xff0c;将所有梦想变为现实&#xff01;它配备了强大的后置 12MP 摄像头和前置 12MP 摄像头&#xff0c;令您的拍摄体验更加出色。苹果还加入了 Apple Pencil 悬停功能&#xff0c;让您的创作更加灵活。 这款 iPad Air 不仅速度加…

武汉凯迪正大—电能质量测试仪功能特点

武汉凯迪正大电能质量测试仪功能特点 1. 仪器是专门用于检测电网中发生波形畸变、谐波含量、三相不平衡等电能质量问题的高精度测试仪器&#xff1b;同时还具备电参量测试、矢量分析的功能。 2. 可精确测量电压、电流、有功功率、无功功率、相角、功率因数、频率等多种电参量…

PowerBI实用技巧——案例十一 (根据所选日期动态滚动显示日期)

分享一波常用的日期动态滚动显示的小技巧,类似的方法还有很多&#xff0c;这里举3个小案例参考。 一、根据所选日期滚动显示近12月的数据&#xff08;日期为年月格式&#xff09; 效果图&#xff1a; 实现逻辑&#xff1a; rolloing_month //所选日期为年月格式,根据所选日…

为什么跑腿越来越受到年轻人的青睐

跑腿服务越来越受到年轻人的青睐&#xff0c;主要源于以下几个方面的原因&#xff1a; 1. 便捷快速&#xff1a;在快节奏的现代生活中&#xff0c;年轻人追求的是效率和速度。跑腿服务提供了一种即时、便捷的解决方案&#xff0c;使他们能够在繁忙的生活和工作中节省时间和精力…