JSR-303 Spring MVC 訊息國際化 配置
本文中使用的個軟體版本(見最下方截圖):
Spring:4.1.1
JSR 303 Validator: 1.0.0
JSR 303 Validator實現:hibernate 4.3.2
說明:為什麼這裡選擇hibernate 4.3.2,而沒有選擇更高版本?
原因:Hibernate Validator 4.X 版本是完全基於JSR303;5.X版本還實現了JSR349的特性。
Hibernate Validator 3.x and 4.x/5.x are different codebases.
Hibernate Validator is the original validation framework from the Hibernate team and is now referred to as "Legacy Hibernate Validator".
Hibernate Validator 4.x is the reference implementation of Bean Validation 1.0 (JSR 303),while Hibernate Validator 5.x is the reference implementation of Bean Validation 1.1 (JSR 349). Active development happens on the 5.x codebase.
一、使用Hibernate Validator內建的國際化訊息配置
1. 引入所需要的包
2. 配置
- <mvc:annotation-driven
- <mvc:annotation-driven/>
3. 在需要驗證的物件屬性欄位上用註解校驗
- <pre name="code"class="java">publicclass Application {
- privateint appId;
- privateint appServerId;
- @NotBlank
- private String appName;
- @NotBlank
- private String appUri;
- private String logFilePrefix;
- private String logFileSuffixPattern;
- <pre name="code"class="java">publicclass Application {
- privateint appId;
- privateint appServerId;
- @NotBlank
- private String appName;
- @NotBlank
- private String appUri;
- private String logFilePrefix;
- private String logFileSuffixPattern;
4. 在Controller中編寫驗證邏輯
- @RequestMapping(value = "/create", method = RequestMethod.POST)
- public String createApp(@Valid@ModelAttribute("app") Application application, BindingResult bindingResult, Model model) {
- if (bindingResult.hasErrors()) {
- return"app/create";
- }
- this.applicationService.addApplication(application);
- return"redirect:app/list";
- }
- @RequestMapping(value = "/create", method = RequestMethod.POST)
- public String createApp(@Valid@ModelAttribute("app") Application application, BindingResult bindingResult, Model model) {
- if (bindingResult.hasErrors()) {
- return"app/create";
- }
- this.applicationService.addApplication(application);
- return"redirect:app/list";
- }
5. 頁面錯誤訊息配置
- <body>
- <sf:formaction="/finder/app/create"method="post"modelAttribute="app">
- appServerId:<sf:selectpath="appServerId"items="${appServers}"itemValue="appServerId"itemLabel="appServerUri"/><br/>
- appName:<sf:inputpath="appName"id="appName"/><sf:errorspath="appName"/><br/>
- appUri:<sf:inputpath="appUri"id="appUri"/><sf:errorspath="appUri"/><br/>
- logFilePrefix:<sf:inputpath="logFilePrefix"id="logFilePrefix"/><sf:errorspath="logFilePrefix"/><br/>
- logFileSuffixPattern:<sf:inputpath="logFileSuffixPattern"id="logFileSuffixPattern"/><sf:errorspath="logFileSuffixPattern"/><br/>
- <inputtype="submit"name="submit"value="submit"/>
- </sf:form>
- </body>
- <body>
- <sf:formaction="/finder/app/create"method="post"modelAttribute="app">
- appServerId:<sf:selectpath="appServerId"items="${appServers}"itemValue="appServerId"itemLabel="appServerUri"/><br/>
- appName:<sf:inputpath="appName"id="appName"/><sf:errorspath="appName"/><br/>
- appUri:<sf:inputpath="appUri"id="appUri"/><sf:errorspath="appUri"/><br/>
- logFilePrefix:<sf:inputpath="logFilePrefix"id="logFilePrefix"/><sf:errorspath="logFilePrefix"/><br/>
- logFileSuffixPattern:<sf:inputpath="logFileSuffixPattern"id="logFileSuffixPattern"/><sf:errorspath="logFileSuffixPattern"/><br/>
- <inputtype="submit"name="submit"value="submit"/>
- </sf:form>
- </body>
6. 測試驗證訊息
以上的方式是預設從Hibernate Validator包中的訊息配置檔案中讀取的:
當我們需要自定義錯誤訊息我們有兩種方法:
1. 重寫Hibernate Validator預設的訊息配置檔案,在其中自定義錯誤訊息。
2. 自由指定錯誤訊息basename,自定義錯誤訊息。
二、 重寫Hibernate Validator預設的訊息配置檔案,在其中自定義錯誤訊息
此時我們只需要在classpath的根路徑下放置一個同名的ValidationMessages屬性檔案,在其中自定義我們的國際化訊息就可以實現。
1. 在跟路徑下建同名配置檔案,自定義錯誤訊息
2. 驗證物件上指定message的key
- publicclass Application {
- privateint appId;
- privateint appServerId;
- @NotBlank(message="{appName.not.blank}")
- private String appName;
- @NotBlank(message="{appUri.not.blank}")
- private String appUri;
- private String logFilePrefix;
- private String logFileSuffixPattern;
- publicclass Application {
- privateint appId;
- privateint appServerId;
- @NotBlank(message="{appName.not.blank}")
- private String appName;
- @NotBlank(message="{appUri.not.blank}")
- private String appUri;
- private String logFilePrefix;
- private String logFileSuffixPattern;
3. 驗證錯誤訊息
三、自定義國際化訊息配置
重寫Hibernate Validator國際化訊息配置雖然可以達到我們首先自定義訊息鍵值對的目的,但是這種方式約束了我們國際化訊息檔案的檔案位置,這不利於專案結構管理。
我們希望能自定義國際化訊息檔案的路徑、檔名和錯誤訊息鍵值對。
1. 更改配置
- <prename="code"class="html"><!-- i18n messages -->
- <beanid="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">
- <propertyname="defaultEncoding"value="UTF-8"/>
- <!-- you can config a single basename -->
- <!--<property name="basename" value="" />-->
- <!-- multi basename -->
- <propertyname="basenames">
- <list>
- <value>org/dsw/config/i18n/ValidationMessages</value>
- <value>org/dsw/config/i18n/BusinessMessages</value>
- </list>
- </property>
- </bean>
- <!-- JSR 303 Validator -->
- <beanid="validator"class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
- <propertyname="providerClass"value="org.hibernate.validator.HibernateValidator"/>
- <propertyname="validationMessageSource"ref="messageSource"/>
- </bean>
- <mvc:annotation-drivenvalidator="validator"/>
- <prename="code"class="html"><!-- i18n messages -->
- <beanid="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">
- <propertyname="defaultEncoding"value="UTF-8"/>
- <!-- you can config a single basename -->
- <!--<property name="basename" value="" />-->
- <!-- multi basename -->
- <propertyname="basenames">
- <list>
- <value>org/dsw/config/i18n/ValidationMessages</value>
- <value>org/dsw/config/i18n/BusinessMessages</value>
- </list>
- </property>
- </bean>
- <!-- JSR 303 Validator -->
- <beanid="validator"class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
- <propertyname="providerClass"value="org.hibernate.validator.HibernateValidator"/>
- <propertyname="validationMessageSource"ref="messageSource"/>
- </bean>
- <mvc:annotation-drivenvalidator="validator"/>
2. 自定義國際化訊息檔案的路徑、檔名和錯誤訊息鍵值對。
3. 驗證錯誤訊息
軟體版本: