跟杨春娟学SpringBoot笔记:国际化之页面和controller
完成:第一遍
1.SpringBoot如何配置国际化配置页面和controller?
步骤一:在src/main/resources下创建新的Folder,名字为i18n,用于国际化
步骤二: 创建message文件,名字为message.properties
welcome=Hello! Welcome to my website.
wel.text=Hello! Welcome {0}({1}) to my website.
步骤三:创建message_en_US.properties
message_en_US.properties
welcome=Hello! Welcome to my website.
wel.text=Hello! Welcome {0}({1}) to my website.
步骤四:创建message_zh_CN.properties
message_zh_CN.properties
welcome=\u4F60\u597D\uFF01\u6B22\u8FCE\u6765\u5230\u6211\u4EEC\u7684\u4E16\u754C\u3002
wel.text=\u4F60\u597D\uFF0C\u6B22\u8FCE{0}({1})
步骤五:i18message.html
i18message.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>This is a Thymeleaf page</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
This is Thymeleaf page!
//国际化用#{}而不是${}
<p th:text="#{welcome}"></p>
<p th:text="${wel}"></p>
This is parameter from properties file
<p th:text="#{wel.text('Cherry', 'China')}"></p>
This is parameter show from controller
<p th:text="${welWithParams}"></p>
<p th:text="${defaultValue}"></p>
</body>
</html>
步骤六:新建MessageController.java
MessageController.java
package com.springboot.demo.SpringBootDemoProject.i18n;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("m")
public class MessageController {
/*
* @Autowired private MessageSource messageSource;
*/
@Autowired
private MessageUtil messageUtil;
@GetMapping("show")
public String show(ModelMap model, Locale locale) {
String wel = messageUtil.getMessage("welcome");
//messageSource.getMessage("welcome", null, locale);
String[] params = {"Cherry", "China"};
String welWithParams = messageUtil.getMessage("wel.text", params);
String defaultValue = messageUtil.getMessage("wel.slije", null, "This is a default value");
model.addAttribute("wel", wel);
model.addAttribute("welWithParams", welWithParams);
model.addAttribute("defaultValue", defaultValue);
return "i18message";
}
}
步骤七:在application-dev.yml的spring:下添加messages(这里messages表示国际化的文件名)
messages:
basename: i18n/message
encoding: UTF-8