Spring Boot + Freemarker多語言國際化的實現

最近在寫一些Web的東西,技術上採用了Spring Boot + Bootstrap + jQuery + Freemarker。過程當中查了大量的資料,也感覺到了前端技術的分裂,每種東西都有N種實現,組合起來,每種解決方案的資料卻頗有限。html

這篇文章記錄下多語言國際化的實現,以支持中英文爲例。前端

首先是頁面內容的國際化

1.定義頁面文本配置文件的路徑,在application.properties裏添加spring.messages.basename=i18n/messagesjava

2.在resources/目錄下建立上述目錄,添加3個配置文件messages.propertiesmessages_zh.propertiesmessages_en.properties,分別對應默認,中文和英文配置,完整路徑爲resources/i18n/messages.properties正則表達式

3.在配置文件裏定義每條須要國際化的文本,好比中文 index.title=麥希工具 - 您身邊的助手,英文Meta Tool - Your Best Assistantspring

4.在Freemarker文件裏使用<@spring.message ""/>來輸出文本,好比<title><@spring.message "index.title"/></title>後端

再說下驗證內容的國際化

所謂驗證內容,就是好比在填Form表單的時候,有些字段有格式或數值等的要求,表單提交時,應該驗證數據是否符合要求。驗證又分前端驗證和後端驗證,通常結合使用。app

前端用來驗證格式(必須是數字/英文/郵件)等,如:ide

<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對象裏,以添加註解的形式實現,如:ui

@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.propertiesValidationMessages_zh.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

相關文章
相關標籤/搜索