如何配置国际化配置页面和controller

跟杨春娟学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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值