最近在写一些 web 的东西, 技术上采用了 Spring Boot + Bootstrap + jQuery + Freemarker 过程中查了大量的资料, 也感受到了前端技术的分裂, 每种东西都有 N 种实现, 组合起来, 每种解决方案的资料却很有限
这篇文章记录下多语言国际化的实现, 以支持中英文为例
首先是页面内容的国际化
1. 定义页面文本配置文件的路径, 在 application.properties 里添加
spring.messages.basename=i18n/messages
2. 在 resources / 目录下创建上述目录, 添加 3 个配置文件 messages.propertiesmessages_zh.propertiesmessages_en.properties, 分别对应默认, 中文和英文配置, 完整路径为 resources/i18n/messages.properties
3. 在配置文件里定义每条需要国际化的文本, 比如中文
index.title = 麦希工具 - 您身边的助手
, 英文
Meta Tool - Your Best Assistant
4. 在 Freemarker 文件里使用 <@spring.message ""/> 来输出文本, 比如
<title><@spring.message "index.title"/></title>
再说下验证内容的国际化
所谓验证内容, 就是比如在填 Form 表单的时候, 有些字段有格式或数值等的要求, 表单提交时, 应该验证数据是否符合要求验证又分前端验证和后端验证, 一般结合使用
前端用来验证格式 (必须是数字 / 英文 / 邮件) 等, 如:
<input type="text" name="height" id="height" class="form-control col-2" placeholder=""pattern="^[1-9][0-9]{2}$" required>
这里 pattern 使用正则表达式, 定义了输入框输入字符的范围和数量
后端用来验证数值 (必须大于 18 岁) 等, 可以在 Spring Boot 的 VO 对象里, 以添加注解的形式实现, 如:
- @Min(value = 100, message = "不能低于 100cm")
- @Max(value = 250, message = "不能高于 250cm")
- private String height;
这里就出现了问题, 即注解也应该采用配置文件的形式, 以支持多语言切换, 这就是验证内容的国际化
1. 定义验证文本配置文件的路径, 在 application.properties 里添加
spring.messages.basename=i18n/messages,i18n/ValidationMessages
, 前面的是第一节的页面文本, 后面的是验证文本
2. 在 resources / 目录下创建上述目录, 添加 3 个配置文件 ValidationMessages.propertiesValidationMessageszh.propertiesValidationMessages_en.properties, 分别对应默认, 中文和英文配置, 完整路径为 resources/i18n/ValidationMessages.properties
3. 在配置文件里定义每条需要国际化的文本, 比如中文
vm.bmi.height.lower = 不能低于 100cm
, 英文
vm.bmi.height.lower=Can Not Lower Than 100cm
4. 与页面文本相比, 这里要多做一步, 即在代码里覆盖默认验证器的配置, 在代码根目录添加以下文件:
- @Configuration
- public class CustomConfiguration implements WebMvcConfigurer {
- @Autowired
- private MessageSource messageSource;
- @Override
- public Validator getValidator() {
- return localValidatorFactoryBean();
- }
- @Bean
- public LocalValidatorFactoryBean localValidatorFactoryBean() {
- LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
- validator.setValidationMessageSource(messageSource);
- return validator;
- }
- }
5. 在接收表达的 VO 对象的属性上, 使用验证文本作为提示
- public class BmiVo {
- @Min(value = 100, message = "{vm.bmi.height.lower}")
- @Max(value = 250, message = "{vm.bmi.height.upper}")
- private String height;
6. 在表单上添加验证失败后的提示, 使用 <@spring.bind ""/> 绑定 VO 对象的属性, 使用 <@spring.showErrors""/> 显示属性验证失败的提示
- <div id="div-height" class="form-group form-row align-items-center">
- <@spring.bind "vo.height" />
- <label for="height" class="col-form-label text-center offset-3 col-2"><@spring.message "bmi.height"/></label>
- <input type="text" name="height" id="height" class="form-control col-2" placeholder=""pattern="^[1-9][0-9]{2}$" required>
- <span class="text-primary text-center col-1">cm</span>
- <span class="text-danger col-4"><@spring.showErrors ""/></span>
- </div>
这样就做到了页面内容和验证内容的多语言国际化支持, 具体示例参看 Meta Tool http://metazion.net/
来源: https://www.cnblogs.com/kaleovon/p/8669642.html