Spring MVC 使用介紹(十三)資料驗證
阿新 • • 發佈:2018-12-07
一、訊息處理功能
Spring提供MessageSource介面用於提供訊息處理功能:
public interface MessageSource { String getMessage(String code, Object[] args, String defaultMessage, Locale locale); String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException; String getMessage(MessageSourceResolvable resolvable, Locale locale)throws NoSuchMessageException; }
Spring提供了兩個預設實現:
StaticMessageSource // 測試用 ResourceBundleMessageSource // 用於生產環境
ApplicationContext
介面擴充套件了MessageSource
介面,當ApplicationContext
被載入時,它會自動在context中查詢已定義為MessageSource
型別的bean。此bean的名稱須為messageSource
。如果找到,那麼所有對上述方法的呼叫將被委託給該bean。否則ApplicationContext
MessageSource
。如果它最終沒有找到任何的訊息源,一個空的StaticMessageSource
將會被例項化,使它能夠接受上述方法的呼叫。
示例如下:
屬性檔案
# exception.properties message.arg=the {0} {1} is requred. # format.properties message=這是一條測試訊息 # format_en_GB.properties message=this is a test
spring 配置(spring-validation.xml)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>format</value> <value>exception</value> </list> </property> <property name="fileEncodings"> <props> <prop key="format">utf-8</prop> </props> </property> </bean> </beans>
測試
public class MessageTest { public static void main(String[] args) { MessageSource ms = new ClassPathXmlApplicationContext("spring-validation.xml"); String msg1 = ms.getMessage("message", null, "yeah", null); String msg2 = ms.getMessage("message.arg", new Object[] { "aa", "bb" }, "yeah", null); // 引數定製 String msg3 = ms.getMessage("message", null, "yeah", Locale.UK); // 支援國際化 System.out.println(msg1); System.out.println(msg2); System.out.println(msg3); } }
執行結果
這是一條測試訊息 the aa bb is requred. this is a test
補充:spring提供了MessageSourceAware介面,用於在bean建立時自動注入MessageSource。
參考:
spring中ResourceBundleMessageSource的配置使用方法