Spring boot with i18n

Spring boot with i18n

节选自《Netkiller Spring Cloud 手札》

i18n 国际化

在 appliction.properties 中配置启用 i18n

spring.messages.basename=message
spring.messages.encoding=UTF-8

创建语言包文件

创建默认语言包文件 message.properties,当匹配不到语言时使用默认配置

member.name=Name
 
 
message_en_US.properties
 
member.name=Name
 
 
message_zh_CN.properties
 
member.name=姓名 

注意:Eclipse 需要安装 properties 编辑工具,否则中文会自动转换成UTF8编码,无法直接阅读。

控制器重引用语言包

RestController

@RestController
public class HomeController {
 @Autowired
 private MessageSource messageSource;

 @GetMapping("/lang")
 public String language() {
 String message = messageSource.getMessage("member.name", null, LocaleContextHolder.getLocale());
 return message;
 }
}

Controller

package cn.netkiller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import java.util.Locale;

@Controller
public class HomeController {

 @Autowired
 private MessageSource messageSource;

 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String index(Locale locale, Model model){

 // add parametrized message from controller
 String welcome = messageSource.getMessage("welcome.message", new Object[]{"Neo Chan"}, locale);
 model.addAttribute("message", welcome);
 
 // obtain locale from LocaleContextHolder
 Locale currentLocale = LocaleContextHolder.getLocale();
 model.addAttribute("locale", currentLocale);
 model.addAttribute("startMeeting", "10:30");
 
 return "index";
 }

} 

参数传递

有时定义语言包会出现一种情况,一个句子中可能存在变量。例如:

恭喜你 XXXX 您已成为我们的会员

这样的需求,如果丁一两个key处理起来会非常麻烦。这里可以定义一个变量,通过参数传递来修改一句话中间的部分。

welcome=Welcom to {0}
 @GetMapping("/lang/args")
 public String welcome() {
 String[] args = { "China" };
 String message = messageSource.getMessage("welcome", args, LocaleContextHolder.getLocale());

 return message;
 }

参数以此类推 {0}, {1} ...... {n}

String welcome = messageSource.getMessage("welcome.message", new Object[]{"Neo chen"}, locale); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

netkiller-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值