Home >Java >javaTutorial >How to configure internationalization page in Spring boot Thymeleaf

How to configure internationalization page in Spring boot Thymeleaf

WBOY
WBOYforward
2023-05-15 21:37:041877browse

1. Write a multi-language internationalization configuration file

Create a folder named i18n under the project's classpath resources, and write the corresponding multi-language internationalization files login.properties and login_zh_CN in the folder as needed. properties and login_en_US.properties files

login.properties

login.tip=Please log in
login.username=username
login.password=password
login.rememberme=Remember me
login.button=Login

login_zh_CN.properties

login.tip=Please log in
login.username=User Name
login.password=Password
login.rememberme=Remember me
login.button=Login

login_en_US.properties

login. tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login

login.properties It is a custom default language configuration file, login_zh_CN.properties is a custom Chinese internationalization file, login_en_US.properties is a custom English internationalization file

It should be noted that the language configuration file recognized by Spring Boot by default is the class messages.properties under the path resources; the names of other language internationalization files must be named strictly in the form of "file prefix name language code country code.properties"

In this example, it is customized under the project class path resources An i18n package is created for unified configuration and management of multi-language configuration files, and the project default language configuration file name is customized as login.properties. Therefore, the internationalized file base name must be configured in the project global configuration file before it can be referenced. Customized internationalization files

2. Write the configuration file

Open the application.properties global configuration file of the project, and add the internationalized file base name setting in the file, with the content such as file

# Configure the internationalized file base name
spring.messages.basename=i18n.login

spring.messages.basename=i18n.login" sets the base name of the custom internationalized file. Among them, i18n means that the internationalized file is relative The location of the project class path resources, login represents the prefix name of the multi-language file. If the developer completely follows the Spring Boot default identification mechanism and writes internationalized files such as messages.properties under the project class path resources, the base name of the internationalized file can be omitted. Configuration

3. Customized regional information parser

After completing the writing and configuration of the multi-language internationalization file in the previous step, you can officially combine the relevant attributes of the Thymeleaf template in the front-end page for internationalization. language settings and display, but this implementation uses the language information in the request header (browser language information) to automatically switch languages ​​by default. Some projects also provide the function of manual language switching, which requires customized regional parsing.

Create a package named com.lagou.config in the project, and create a custom configuration class MyLocalResovel

package com.lagou.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
@Configuration
public class MyLocalResolver implements LocaleResolver {
    // 完成自定义 区域解析方式
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取页面手动传递的语言参数值 : zh_CN   en_US   ""
        String l = request.getParameter("l");
        Locale locale = null;
        if (!StringUtils.isEmpty(l)) {
            // 如果参数不为空,就根据参数值,进行手动语言切换
            String[] s = l.split("_");
            locale = new Locale(s[0], s[1]);
        } else {
            // Accept-Language: zh-CN,zh;q=0.9
            String header = request.getHeader("Accept-Language");
            String[] split = header.split(",");
            String[] split1 = split[0].split("-");
            locale = new Locale(split1[0], split1[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
    // 将自定义的LocaleResolver重新注册成一个类型为LocaleResolver的Bean组件
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocalResolver();
    }
}
# under this package for customizing the internationalized functional area information parser. ##MyLocalResolver The custom regional resolver configuration class implements the LocaleResolver interface, and rewrites the resolveLocale() method for custom language resolution. Finally, the @Bean annotation is used to register the current configuration class as a LocaleResolver in the Spring container. Bean component, so that the default LocaleResolver component can be overridden. Among them, in the resolveLocale() method, the request parameter l and the request header parameter are obtained respectively according to different needs (manual switching of language information, browser request header automatic switching of language information) Accept-Language, and then when the request parameter l is not empty, the language carried by the l parameter will be used as the standard for language switching. Otherwise, automatic switching will be customized through the request header information.

It should be noted that, When manually switching the language of the request parameter l, the underscore "_" is used for cutting, which is determined by the format of the multi-language configuration file (such as login_zh_CN.properties); while in the language of the request header parameter Accept-Language When automatically switching assembly, the dash "-" is used for cutting, which is determined by the request header information style sent by the browser (for example, Accept-Language: en-US,en;q=0.9,zh-CN ;q=0.8,zh;q=0.7)

4. Page internationalization uses

Open the user login page login.html in the project templates template folder, and combine it with the Thymeleaf template engine to implement the internationalization function

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-
fit=no">
        <title>用户登录界面</title>
        <link th:href="@{/login/css/bootstrap.min.css}" rel="external nofollow"  rel="stylesheet">
        <link th:href="@{/login/css/signin.css}" rel="external nofollow"  rel="stylesheet">
    </head>
    <body class="text-center">
        <!-- 用户登录form表单 -->
        <form class="form-signin">
            <img  class="mb-4" th:src="@{/login/img/login.jpg}"    style="max-width:90%"  style="max-width:90%" alt="How to configure internationalization page in Spring boot Thymeleaf" >
            <h2 class="h4 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h2>
            <input type="text" class="form-control"
                   th:placeholder="#{login.username}" required="" autofocus="">
            <input type="password" class="form-control"
                   th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
                    <input type="checkbox" value="remember-me" > [[#{login.rememberme}]]
                </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
            <p class="mt-5 mb-3 text-muted">© <span
                    th:text="${currentYear}">2019</span>-<span
                    th:text="${currentYear}+1">2020</span></p>
            <a class="btn btn-sm" th:href="@{/toLoginPage(l=&#39;zh_CN&#39;)}" rel="external nofollow" >中文</a> <!--注意这个路径是我们controller访问页面的路径,不同的是这次携带了参数,可以帮我们用来区分locale-->
            <a class="btn btn-sm" th:href="@{/toLoginPage(l=&#39;en_US&#39;)}" rel="external nofollow" >English</a>
        </form>
    </body>
</html>

Use the #{} message expression of the Thymeleaf template Set up some information for international display. When setting the rememberme internationalization, the rememberme that needs to be internationalized is outside the input tag, so the inline expression [[#login.rememberme}]] is used here to dynamically obtain the login.rememberme information in the internationalization file. In addition, a functional link for manual language switching between Chinese and English is provided at the end of the form. When the link is clicked, the national language parameters will be carried to request a jump to the "/" path, and manual language switching will be performed through the customized regional parser in the background.

Note: The controller control layer processing is omitted

5. Integration effect test

How to configure internationalization page in Spring boot Thymeleaf

#After click

How to configure internationalization page in Spring boot Thymeleaf

When clicking the "English" link for language internationalization switching, the specified "l=zh_CN" parameter is carried. The parsing method in the background customized regional parser configuration class MyLocalResovel will be based on Customize rules for language switching, thereby achieving the effect of manual switching of international languages

The above is the detailed content of How to configure internationalization page in Spring boot Thymeleaf. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete