47. Springboot의 국제 메시지 지원 - 브라우저에서 선택한 언어에 따라 프로젝트의 일부 프롬프트 정보가 언어 선택에 따라 표시됩니다.

springboot의 국제화 역시 spring mvc를 기반으로 합니다.

Springboot의 국제 메시지 지원 - 브라우저에서 선택한 언어에 따라 프로젝트의 일부 프롬프트 정보가 언어 선택에 따라 표시됩니다.

국유화된 자동 구성을 요약하면
기능 구현은 다음과 같습니다.
예를 들어 로그인 페이지의 경우 브라우저에서 언어를 중국어로 선택하면 로그인 페이지의 모든 프롬프트 메시지가 중국어로 표시됩니다.
브라우저 언어로 영어를 선택한 경우 로그인 페이지의 모든 프롬프트 메시지는 영어로 표시됩니다.
이러한 프롬프트는 속성 구성 파일에 기록됩니다.

★국제 자동 구성

Spring Boot는 국제화와 관련된 구성 속성을 읽는 역할을 하는 국제화 자동 구성을 위한 MessageSourceProperties 클래스를 제공합니다.

Spring Boot의 자동 구성은 지정된 기본 이름을 가진 기본 국제화 리소스 파일(언어 및 국가와 무관한 국제화 리소스)이 존재하는 경우에만 적용됩니다. 예를 들어 spring.messages.basename=mess를 구성합니다.

즉, 제공만 하면

appMess_zh_CN.properties(중국어 간체 리소스 파일)

appMess_en_US.properties(미국 영어 리소스 파일),

국제화를 위한 자동 구성은 적용되지 않으며
기본 appMess.properties 파일이 제공되는 경우에만 적용됩니다.

코드 데모:
적용하려면 기본값이 필요합니다.
여기에 이미지 설명을 삽입하세요.

★ 국제화를 위한 단계

(1) 국제 리소스 파일 작성: basename_언어 코드_국가 코드.properties

(2) 구성 속성을 사용하여 국제화된 리소스 파일을 로드합니다.

Spring Boot는 간단한 구성으로 국제화된 리소스 파일을 로드할 수 있습니다.

 # 加载国际化资源文件
 spring.messages.basename=login_mess
 # 设置使用国际化消息的key作为默认消息
 spring.messages.use-code-as-default-message=true
 # 设置读取国际化消息的字符集是UTF-8
 spring.messages.encoding=UTF-8

(3) 키를 기반으로 국제화된 메시지 출력

두 가지 상황으로 나누어집니다.

 ▲ 在Java组件(如控制器等)中,直接使用容器内的MessageSource Bean(Spring Boot自动配置)
    的getMessage()方法获取国际化消息。

 ▲ 在页面模板中,使用标签或表达式输出国际化消息。比如在Thymeleaf模板中,

    直接使用#{key}即可输出指定key对应的国际化消息。

    【对比】,要输出表达式的值,使用${}。

    【注意】:如果使用devtools来打包Spring Boot项目,最好将*.properties文件设为UTF-8字符集。

코드 데모

요구 사항: 구성 파일의 중국어 및 영어 버전을 생성하여 브라우저가 중국어 또는 영어를 선택할 때 그에 따라 전환할 수 있습니다.

지금은 아무것도 구성되지 않았습니다. 원래 상황을 살펴보겠습니다.
프로젝트를 생성하고, 인덱스 로그인 페이지만 추가하면 됩니다.
그런 다음 기본 중국어이기도 한 일반 언어를 확인하십시오. 그래서 이렇게 표시됩니다.

<h4 th:text="#{login_title}">首页</h4>
不理解为什么当 login_title 没值的时候,不是显示 “首页” 两个字

여기에 이미지 설명을 삽입하세요.

페이지에 국제화된 정보를 출력하기 위한 코드:
1. 로그인 페이지 추가

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>国际化</title>
	<!--  引入css样式,用 link 元素  ,  stylesheet 样式单 , .gz表示是打包的,但是springboot会自动解包 -->
	<!--  引入 BootstrapWeb Jar 中的 CSS 样式  -->
	<link rel="stylesheet" th:href="@{'/webjars/bootstrap/css/bootstrap.min.css'}">

	<!--  jquery 放在 bootstrap 前面,因为 bootstrap 需要依赖到 jquery  -->
	<!--  引入 jQuery 的 Web Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/jquery/jquery.min.js'}"></script>

	<!--  引入 BootstrapWeb Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/bootstrap/js/bootstrap.bundle.min.js'}"></script>

	<!--  引入 popper 的 Web Jar 中的 Js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/popper.js/umd/popper.min.js'}"></script>

</head>
<body>
<div class="container">
	<h4 th:text="#{login_title}">首页</h4>
	<div class="text-danger" th:if="${tip != null}" th:text="${tip}"></div>
	<form method="post" th:action="@{/login}">
		<div class="form-group row">
			<label for="username" class="col-sm-3 col-form-label"
				   th:text="#{name_label}">用户名</label>
			<div class="col-sm-9">
				<input type="text" id="username" name="username"
					   class="form-control" th:placeholder="#{'name_hint'}">
			</div>
		</div>
		<div class="form-group row">
			<label for="pass" class="col-sm-3 col-form-label"
				   th:text="#{password_label}">密码</label>
			<div class="col-sm-9">
				<input type="password" id="pass" name="pass"
					   class="form-control" th:placeholder="#{'password_hint'}">
			</div>
		</div>
		<div class="form-group row">
			<div class="col-sm-6 text-right">
				<button type="submit" class="btn btn-primary"
						th:text="#{login_btn}">登录</button>
			</div>
			<div class="col-sm-6">
				<button type="reset" class="btn btn-danger"
						th:text="#{reset_btn}">重设</button>
			</div>
		</div>
	</form>
</div>
</body>
</html>

2.
국제 리소스 파일 작성: basename_언어 code_country code.properties
여기에 이미지 설명을 삽입하세요.

3. 구성 속성을 사용하여 국제화된 리소스 파일을 로드합니다.

Spring Boot는 간단한 구성으로 국제화된 리소스 파일을 로드할 수 있습니다.
로드하려면 이를 구성해야 합니다.

#加载国际化资源文件
spring.messages.basename=appMess
#设置使用国际化消息的key作为默认消息
spring.messages.use-code-as-default-message=true
#设置读取国际化消息的字符集是 UTF-8
spring.messages.encoding=UTF-8
#设置消息的缓存时间--单位是秒
spring.messages.cache-duration=7200

여기에 이미지 설명을 삽입하세요.

이러한 속성은 이미 구성 클래스에서 해당 값을 얻었음을 확인할 수 있습니다.
여기에 이미지 설명을 삽입하세요.

테스트:
브라우저에서 언어를 전환하면 이 페이지에 해당 텍스트가 표시되며 이는 사용자 정의된 텍스트입니다.
여기에 이미지 설명을 삽입하세요.

국제화 정보를 출력하는 컨트롤러의 코드:


로그인 사용자 이름과 비밀번호를 얻어 로그인 성공 또는 실패 메시지를 반환하도록 컨트롤러와 도메인을 작성합니다 .
반환된 메시지는 국제화된 메시지입니다. 브라우저에서 기본 언어를 영어로 변경하면 코드 표시와 메시지도 영어로 표시된다는 것을 깨닫는 것입니다.
여기에 이미지 설명을 삽입하세요.

로그인 성공 및 실패에 대한 국제 프롬프트 메시지 구성 및 추가
여기에 이미지 설명을 삽입하세요.

프런트엔드 값의 # 및 $ 기호입니다.
여기에 이미지 설명을 삽입하세요.

전체 코드:

애플리케이션.속성

#加载国际化资源文件
spring.messages.basename=appMess
#设置使用国际化消息的key作为默认消息
spring.messages.use-code-as-default-message=true
#设置读取国际化消息的字符集是 UTF-8
spring.messages.encoding=UTF-8
#设置消息的缓存时间--单位是秒
spring.messages.cache-duration=7200

appMess.properties

이 구성에서는 아무 것도 작성할 필요가 없습니다. 이것이 기본값이지만 국제 메시징 기능이 적용되려면 반드시 있어야 합니다.

appMess_zh_CN.properties

login_title=登录页面
name_label=用户名
name_hint=请输入用户名
password_label=密码
password_hint=请输入密码
login_btn=登录
reset_btn=重设
#{
    
    0} 占位符
welcome={
    
    0}, 欢迎登录学习
failure=用户名和密码不匹配

appMess_en_US.properties

login_title=Login Page
name_label=User Name
name_hint=Please input User Name
password_label=Password
password_hint=Please input Password
login_btn=Login
reset_btn=Reset
#{
    
    0} 占位符
welcome={
    
    0}, Welcome to study
failure=sorry,password and username not matched

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>国际化</title>
	<!--  引入css样式,用 link 元素  ,  stylesheet 样式单 , .gz表示是打包的,但是springboot会自动解包 -->
	<!--  引入 Bootstrap 的 Web Jar 中的 CSS 样式  -->
	<link rel="stylesheet" th:href="@{'/webjars/bootstrap/css/bootstrap.min.css'}">

	<!--  jquery 放在 bootstrap 前面,因为 bootstrap 需要依赖到 jquery  -->
	<!--  引入 jQuery 的 Web Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/jquery/jquery.min.js'}"></script>

	<!--  引入 Bootstrap 的 Web Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/bootstrap/js/bootstrap.bundle.min.js'}"></script>

	<!--  引入 popper 的 Web Jar 中的 Js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/popper.js/umd/popper.min.js'}"></script>

</head>
<body>
<div class="container">
	<h4 th:text="#{login_title}">首页</h4>

	<div class="text-danger" th:if="${tip != null}" th:text="${tip}"></div>

	<form method="post" th:action="@{/login}">
		<div class="form-group row">
			<label for="username" class="col-sm-3 col-form-label"
				   th:text="#{name_label}">用户名</label>
			<div class="col-sm-9">
				<input type="text" id="username" name="username"
					   class="form-control" th:placeholder="#{'name_hint'}">
			</div>
		</div>
		<div class="form-group row">
			<label for="password" class="col-sm-3 col-form-label"
				   th:text="#{password_label}">密码</label>
			<div class="col-sm-9">
				<input type="password" id="password" name="password"
					   class="form-control" th:placeholder="#{'password_hint'}">
			</div>
		</div>
		<div class="form-group row">
			<div class="col-sm-6 text-right">
				<button type="submit" class="btn btn-primary"
						th:text="#{login_btn}">登录</button>
			</div>
			<div class="col-sm-6">
				<button type="reset" class="btn btn-danger"
						th:text="#{reset_btn}">重设</button>
			</div>
		</div>
	</form>
</div>
</body>
</html>

성공.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>登录成功</title>
	<!--  引入css样式,用 link 元素  ,  stylesheet 样式单 , .gz表示是打包的,但是springboot会自动解包 -->
	<!--  引入 Bootstrap 的 Web Jar 中的 CSS 样式  -->
	<link rel="stylesheet" th:href="@{'/webjars/bootstrap/css/bootstrap.min.css'}">

	<!--  jquery 放在 bootstrap 前面,因为 bootstrap 需要依赖到 jquery  -->
	<!--  引入 jQuery 的 Web Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/jquery/jquery.min.js'}"></script>

	<!--  引入 Bootstrap 的 Web Jar 中的 js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/bootstrap/js/bootstrap.bundle.min.js'}"></script>

	<!--  引入 popper 的 Web Jar 中的 Js 脚本  -->
	<script type="text/javascript" th:src="@{'/webjars/popper.js/umd/popper.min.js'}"></script>

</head>
<body>
<div class="container">
	<h4 th:text="${tip}">tip</h4>
</div>
</body>
</html>

로그인 컨트롤러

package cn.ljh.i18n.controller;

import cn.ljh.i18n.domain.User;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Locale;

@Controller
public class LoginController
{
    
    
    //依赖注入容器中自动配置 MessageSource Bean , 用于访问国际化信息
    private MessageSource messageSource;
    //构造器注入的方式
    public LoginController(MessageSource messageSource)
    {
    
    
        this.messageSource = messageSource;
    }

    @PostMapping("/login")
    public String proLogin(User user , Model model , Locale locale)
    {
    
    
        if (user.getUsername().equals("ljh") && user.getPassword().equals("123456"))
        {
    
    
            //要添加国际化的提示信息
            //参数1:key   参数2:占位符  参数3:要确定国家地区和语言,用locale这个参数,springboot会自动揣摩
            model.addAttribute("tip",
                    messageSource.getMessage("welcome" , new String[]{
    
    user.getUsername()} , locale));
            return "success";
        }
        //参数2:不需要占位符,直接给个 null 就行
        model.addAttribute("tip",
                messageSource.getMessage("failure" , null , locale));
        return "index";
    }

}

사용자

@Data
public class User
{
    
    
    private Integer id;
    private String username;
    private String password;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_44411039/article/details/132646611
Recomendado
Clasificación