国际化使用参数

国际化文件中:Welcome=\u60A8\u597D\uFF0C{0}\uFF01

页面上:
<h:outputFormat value="#{msgs.welcomeText}">
<f:param value="Hello"/>
<f:param value="Guest"/>
</h:outputFormat>
<h:outputFormat value="{0}, Your name is {1}.">
<f:param value="Hello"/>
<f:param value="Guest"/>
</h:outputFormat>


<h:outputFormat value="#{msg.Welcome}">
<f:param:value="你的东西"/>
</h:outputFormat>
在 Spring Boot 应用中实现国际化(i18n)时,参数传递是一个常见的需求,尤其是在动态内容展示中。可以通过 `MessageSource` 接口来实现带有参数国际化消息处理。 在 Spring Boot 中,国际化消息通常定义在 `messages.properties` 及其语言变体文件中,例如 `messages_en.properties`、`messages_zh.properties` 等。通过 `MessageSource`,可以在控制器中获取带有参数国际化消息。 ### 示例代码 #### 1. 定义国际化消息 在 `src/main/resources` 目录下创建多个语言文件,例如: - `messages_en.properties`: ```properties welcome=Welcome to {0} ``` - `messages_zh.properties`: ```properties welcome=欢迎来到 {0} ``` #### 2. 控制器中使用 `MessageSource` 在控制器中注入 `MessageSource` 并使用 `getMessage` 方法传递参数: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Locale; @RestController public class I18nController { @Autowired private MessageSource messageSource; @GetMapping("/lang/args") public String welcome() { String[] args = { "China" }; Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage("welcome", args, locale); return message; } } ``` #### 3. 测试接口 通过访问 `/lang/args` 接口,并根据请求头中的 `Accept-Language` 参数来决定返回的语言内容。例如: - 请求头为 `Accept-Language: en`,返回: ``` Welcome to China ``` - 请求头为 `Accept-Language: zh`,返回: ``` 欢迎来到 China ``` 通过这种方式,可以灵活地实现国际化消息中的参数传递功能。 ### 国际化消息的动态解析 除了在控制器中手动调用 `getMessage` 方法外,Spring Boot 还支持在 Thymeleaf 模板等视图技术中直接使用参数化消息。例如,在 Thymeleaf 模板中可以这样使用: ```html <p th:text="#{welcome(${country})}">Welcome Message</p> ``` 其中 `${country}` 是动态传递的参数。 ### 国际化配置 为了确保 Spring Boot 正确加载国际化资源,可以在 `application.yml` 中进行相关配置: ```yaml spring: messages: basename: messages encoding: UTF-8 ``` 这段配置指定了国际化资源的基础名称为 `messages`,并确保使用 UTF-8 编码加载资源文件 [^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值