轉自:https://blog.csdn.net/flowingflying/article/details/76358970
spring中ResourceBundleMessageSource的配置使用方法
https://blog.csdn.net/qq_31230529/article/details/48436873javascript
通常性瞭解
咱們在JSTL fmt[1]中已經接觸過國際化i18n,本地化L10n。使用JSTL fmt(Internationalization and Formatting tag library),有一些侷限性:css
- 咱們須要將resource bundles(那些properties文件)放在在eclipse的src/main/resources中,也就是放在了/WEB-INF/classes中。使用classpath的要注意,這個位置是比較特別,JVM將永久緩存,直至web app終結。若是咱們修改文件的內容,修改的內容不會被再次讀入,除非從新加載web app。fmt沒法使用其餘地方的文件或者數據庫。
- fmt經過HTTP請求的Accept-Language來進行判斷使用使用哪一種本地化。咱們如今看到不少網頁有個語言選擇,選擇後,後續的網頁都採用這種語言,fmt在這方面不支持,由於瀏覽器不會根據網頁的選擇而修改其默認語言(進而修改Accept-Language)。
Spring的i18n解決這些問題,並提供更爲便捷的方式;不只在jsp中使用,還能夠在代碼中使用;能夠直接錯誤object(如Throwable)傳遞到本地化API,實現直接本地化錯誤信息。html
Resource bundle和message format
和fmt同樣,Spring的i18n也使用resource bundle(java.util.ResourceBundle)和message format(java.text.MessageFormat),並在resource bundle之上提供抽象的message source,變得更容易本地化。resource bundle是消息中須要本地化的消息格式的集合。java
message format
消息格式(java.text.MessageFormat)含有佔位模板,在運行時被替換。例子以下python
There are {0} cats on the farm. There are {0,number,integer} cats on the farm. The value of Pi to seven significant digits is {0,number,#.######}. My birthdate: {0,date,short}. Today is {1,date,long} at {1,time,long}. My birth day: {0,date,MMMMMM-d}. Today is {1,date,MMM d, YYYY} at {1,time,hh:mma). There {0,choice,0#are no cats|1#is one cat|1<are {0,number,integer} cats}.
這些佔位符號(placeholder)是有順序的,替換是按這個順序,而不是語句中出現的順序(語句中的順序原本就是要本地化)。git
With a {0,number,percentage} discount, the final price is {1,number,currency}.
佔位符是能夠帶格式的,下面#表示序號,斜體表示用戶自定義的格式值web
{#} {#,number} {#,number,integer} {#,number,percent} {#,number,currency} {#,number,自定義格式,遵循java.text.DecimalFormat} {#,date} {#,date,short} {#,date,medium} {#,date,long} {#,date,full} {#,date,自定義格式,遵循java.text.SimpleDateFormat} {#,time} {#,time,short} {#,time,medium} {#,time,long} {#,time,full} {#,time,自定義格式,遵循java.text.SimpleDateFormat} {#,choice,自定義格式,遵循java.text.ChoiceFormat}
resource bundle的命名規則
resource bundle是這些message format的集合,通常採用properties文件的方式,key就是message code,value就是message format。例如:spring
alerts.current.date=Current Date and Time: {0,date,full} {0,time,full}
文件的命名規則以下:數據庫
[baseName]_[language]_[script]_[region]_[variant] [baseName]_[language]_[script]_[region] [baseName]_[language]_[script] [baseName]_[language]_[region]_[variant] [baseName]_[language]_[region] 例如labels_en_US.properties [baseName]_[language] 例如labels_en.properties
以上前面的比後面具備優先權。若是隻有baseName,language和variant,最匹配的是第4個,例子爲:baseName_en__JAVAapache
對於JSTL fmt:
- ResourceBundle首先根據指定的bundle名字下載和實例化一個ResourceBundlede擴展類。
- 若是找不到,將當中的"."提到爲"/",加上".properties"的後綴,在classpath中再找,返回一個PropertyResourceBundle類。
- 若是還找不到,使用fallback Locale來產生的可能的bundle名字,再找
- 還找不到,則找尋baseName的類或文件。(即咱們可使用baseName的文件做爲缺省的匹配)
- 還找不到,拋出異常。
若是咱們須要從數據庫中獲取,就須要本身實現ResourceBundle,然而ResourceBundle實例在同一時刻,只能支持一個Locale,它解析message的方法不帶locale參數,所以須要爲不一樣的locale提供不一樣的ResourceBundle實例。這致使實現的複雜。
Spring的message source
Spring的message source在resource bundle之上提供了抽象和封裝,實現了org.springframework.context.MessageSource接口,接口提供了三個方法,能夠看到locale是方法的參數,無需爲不一樣的locale建立不一樣的實例,此外,已經返回解析後的message,無需再根據message format進行解析。
目前,Spring提供連個MessageSource接口的實現:
- org.springframework.context.support.ResourceBundleMessageSource,裏面含有ResourceBundle的集合,使用ResourceBundle的getBundle()來定位資源,所以是和ResourceBundle徹底相同的策略,即資源必須是在classpath下,所以受限不能更新。
- org.springframework.context.support.ReloadableResourceBundleMessageSource,裏面並不含有ResourceBundle,但使用相同的檢測策略,只支持文件,不支持類,能夠放在非calsspath,即reloadable,一般爲/WEB-INF/i18n。
ReloadableResourceBundleMessageSource小例子
設置properties文件
在/WEB-INF/i18n目錄下設置兩個資源文件。
test_en_US.properties
foo.test = Hello, {0} {1} foo.message = This is the default message. Args: {0}, {1}, {2}.
test_zh_CN.properties文件須要注意,在eclipse下,properties文件缺省採用ISO-8859-1編碼,例子以下
foo.test = \u60A8\u597D, {1} {0}
這樣看簡直是瘋狂,所以,咱們首先要將文件編碼改成UTF-8等能夠看中文的方式,點擊該文件,按右鍵選擇Properties,而後進行修改。
foo.test = 您好, {1} {0} foo.message = 這是缺省消息,參數: {0}, {1}, {2}.
配置messageSource Bean
咱們在root上下文中進行設置
public class RootContextConfiguration implements AsyncConfigurer,SchedulingConfigurer{ //... 略 ... @Bean //【注意】這個bean的名字必須叫messageSource,不然無效 public MessageSource messageSource(){ ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); //若是設置爲-1,表示Cache forever。通常生產環境下采用-1,開發環境爲了方便調測採用某個正整數,規範地咱們可經過profile來定義 messageSource.setCacheSeconds(5); /* 設置缺省的資源文件的編碼, * 若是個別文件採用其餘編碼(不適用缺省編碼,但通常咱們應統一進行設置),能夠經過setFileEncoding()來指定 * Properties properties = new Properties(); * properties.setProperty("/WEB-INF/i18n/test_zh_CN", "GBK"); * messageSource.setFileEncodings(properties); */ messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name()); //設置properties文件的basename,以便找到響應的資源文件 messageSource.setBasenames("/WEB-INF/i18n/messages", "/WEB-INF/i18n/errors","/WEB-INF/i18n/test"); return messageSource; } }
小例子中咱們採用文件做爲資源,在實際中也能夠會使用到數據庫,例如NoSQL倉庫,咱們須要構建自定義的message source,這在後面介紹。
在代碼中使用
@Service public class MyTestService implements TestService{ private static final Logger logger = LogManager.getLogger(); @Inject MessageSource messageSource; @Override public void testSourceMessage() { String msg = this.messageSource.getMessage("foo.message", new Object[]{"One","Two","Three"}, Locale.US); logger.info(msg); msg = this.messageSource.getMessage("foo.message", new Object[]{"一","二","三"}, Locale.getDefault()); logger.info(msg); msg = this.messageSource.getMessage("foo.lable", new Object[]{"Hi"}, "{0}, my friend", Locale.ENGLISH); logger.info(msg); } }
輸出結果:
14:43:36.789 [INFO ] MyTestService:20 testSourceMessage() - This is the default message. Args: One, Two, Three. 14:43:36.790 [INFO ] MyTestService:22 testSourceMessage() - 這是缺省消息,參數: 一, 二, 三. 14:43:36.791 [INFO ] MyTestService:24 testSourceMessage() - Hi, my friend
Locale.US將匹配test_en_US.properties,若是咱們設置Locale.ENGLISH,因爲並無test_en.propertiesst,將採用缺省的Locale值,即匹配了test_zh_CN.properties,若是仍沒有找到,採用default message的參數。
在jsp中使用
測試案例的Controller相關代碼以下:
@RequestMapping(value = "/test", method = RequestMethod.GET) public String test(Map<String, Object> model){ model.put("firstName", "San"); model.put("lastName", "Zhang"); return "home/test"; }
在jsp中使用spring:message,以下。使用方法參考文檔[2]
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> ... ... <spring:message code="foo.test"> <spring:argument value="${firstName}" /> <spring:argument value="${lastName}" /> </spring:message> <!-- 設置htmlEscape,確保安全;若是foo.test沒有找到,採用缺省的text內容--> <spring:message code="foo.test" htmlEscape="true" text="Hi, {0} {1}"> ... ... </spring:message> <!-- 能夠經過arguments一次性將全部參數列上,分隔符缺省是逗號,也能夠經過argumentSeparator設定分隔符--> <spring:message code="foo.test" arguments="A,B" /> <spring:message code="foo.test" argumentSeparator=":" arguments="A:B" /> <!-- 直接傳遞MessageSourceResolvable對象,具體在後面介紹--> <spring:message message="${exception}" />
咱們能夠獲得頁面輸出您好, Zhang San
。spring:message和fmt:message很類似,一樣有htmlEscape屬性,缺省爲false。若是某個jsp中有大量須要htmlEscape的spring:message,咱們能夠在jsp中設置 <spring:htmlEscape defaultHtmlEscape="true" />
,這將對以後的代碼有效。若是咱們整個app都有大量的htmlEscape,咱們能夠在web.xml中配置。
<context-param> <param-name>defaultHtmlEscape</param-name> <param-value>true</param-value> </context-param>
咱們仍能夠沿用JSTL fmt tag,以下,也可獲得正確的輸出。
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> ... ... <fmt:message key="foo.test"> <fmt:param value="${firstName}" /> <fmt:param value="${lastName}" /> </fmt:message> ... ...
咱們去查看log,不管是採用spring的tag仍是fmt的tag,log是一樣的,同時經過ReloadableResourceBundleMessageSource bean來進行處理。
16:23:45.837 [TRACE] (Spring) JstlView - Rendering view with name 'home/test' with model {firstName=San, lastName=Zhang} and static attributes {} 16:23:45.837 [DEBUG] (Spring) JstlView - Added model object 'firstName' of type [java.lang.String] to request in view with name 'home/test' 16:23:45.837 [DEBUG] (Spring) JstlView - Added model object 'lastName' of type [java.lang.String] to request in view with name 'home/test' 16:23:45.837 [DEBUG] (Spring) JstlView - Forwarding to resource [/WEB-INF/jsp/view/home/test.jsp] in InternalResourceView 'home/test' 16:23:45.859 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - Re-caching properties for filename [/WEB-INF/i18n/messages_zh_CN] - file hasn't been modified 16:23:45.859 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - No properties file found for [/WEB-INF/i18n/messages_zh] - neither plain properties nor XML 16:23:45.859 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - No properties file found for [/WEB-INF/i18n/messages] - neither plain properties nor XML 16:23:45.862 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - Re-caching properties for filename [/WEB-INF/i18n/errors_zh_CN] - file hasn't been modified 16:23:45.863 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - No properties file found for [/WEB-INF/i18n/errors_zh] - neither plain properties nor XML 16:23:45.863 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - No properties file found for [/WEB-INF/i18n/errors] - neither plain properties nor XML 16:23:45.866 [DEBUG] (Spring) ReloadableResourceBundleMessageSource - Re-caching properties for filename [/WEB-INF/i18n/test_zh_CN] - file hasn't been modified 16:23:45.866 [TRACE] (Spring) DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@e05013 16:23:45.866 [DEBUG] (Spring) DispatcherServlet - Successfully completed request
沒有通過JstlView的jsp
採用<spring>和<fmt>貌似同樣,可是fmt是經過spring框架的ReloadableResourceBundleMessageSource來實現,若是有某個jsp文件,並無通過spring框架,fmt就是標準的fmt,不能讀取/WEB-INF/i18n目錄下的資源文件,會報異常。這種狀況也是常有的,例如error.jsp就可能不經過spring框架。對於這種狀況有兩種解決方案:
- 採用spring tag,將經過spring框架使用MessageSource。
- 使用filter,強制全部的jsp都經過spring框架。
第一種方式很簡單,推薦使用。若是有與某種緣由不能使用第一種方式,須要採用filter,咱們首先要將filter設置爲spring的bean,這樣它才能夠注入message source,方式和以前學習的Listener同樣。咱們在Bootstrap初始化root context後代碼設置filter,這樣確保能夠注入root context中的bean,設置相關的jsp通過它。下面是相關filter的代碼:
public class JstlLocalizationContextFilter implements Filter { private MessageSource jstlMessageSource; @Inject MessageSource messageSource; public JstlLocalizationContextFilter() { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException { // Exposes JSTL-specific request attributes specifying locale and resource bundle for // JSTL's formatting and message tags,using Spring's locale and MessageSource. JstlUtils.exposeLocalizationContext((HttpServletRequest)request, this.jstlMessageSource ); chain.doFilter(request, response); } @Override public void init(FilterConfig fConfig) throws ServletException { ServletContext servletContext = fConfig.getServletContext(); WebApplicationContext rootContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); AutowireCapableBeanFactory factory = rootContext.getAutowireCapableBeanFactory(); factory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,true); factory.initializeBean(this,"JstlLocalizationContextFilter"); /* 【1】第一個參數servletContext首先檢查JSTL的"javax.servlet.jsp.jstl.fmt.localizationContext" * 的context-param(web.xml),若是有設置,生成相應的ResourceBundleMessageSource實例。 * 【2】第二個參數爲spring的MessageSource。 * 將根據這兩個參數得到子message source */ this.jstlMessageSource = JstlUtils.getJstlAwareMessageSource( servletContext, this.messageSource ); } }