2012-01-10 55 views

回答

19

config/spring/resources.groovy中定義一個LocaleResolver bean來設置默認語言環境。

beans = { 
    localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) { 
     defaultLocale = new Locale("de","DE") 
     java.util.Locale.setDefault(defaultLocale) 
    } 
} 

如果你沒有對付lang參數這是有用的 - 否則它會得到重寫。甚至忽略lang參數值,你可以在每次要求設置在Filter語言環境:

import org.springframework.web.servlet.support.RequestContextUtils as RCU 
... 
def filters = { 
    all(controller:'*', action:'*') { 

     before = { 
      def locale = new Locale("sv","SV") 
      RCU.getLocaleResolver(request).setLocale(request, response, locale)     
     } 

    } 
} 

這種做法似乎有些重複的語言環境對每個請求重新設置。通過配置選項禁用瀏覽器語言環境檢測會更加優雅。

+1

這不是對上述問題的回答。 ArmlessJohn特別要求能夠*覆蓋用戶的語言設置。這只是設置默認值。請閱讀您再次鏈接的答案。 – OverZealous 2012-01-11 03:50:41

+0

感謝您的通知 - 我已經相應地更新了我的答案。 – david 2012-01-11 13:52:11

+1

小心! java.util.Locale.setDefault(defaultLocale)將改變整個JVM的默認語言環境,這可能是非常糟糕的,因爲很多代碼在所有語言環境中都認爲「i」.toUpperCase()。equals(「I」) 。它不... 許多聰明的實用程序會做出這樣的假設。 – JesperSM 2014-11-18 22:36:34

5

刪除所有messages_xx.properties文件並只保留messages.properties文件。 這是缺省消息捆綁包,如果系統找不到正確的消息捆綁包,系統將始終回退到該缺省消息捆綁包。

通過這種方式,您仍然可以使用消息(並因此保留將應用程序國有化的選項),但用戶將始終使用相同的語言。

3

Grails的默認LocaleResolverSessionLocaleResolver。如果您想始終使用de_DE,則可以將其更改爲FixedLocaleResolver

beans { 
    localeResolver(FixedLocaleResolver) { 
     locale = new Locale("de", "DE") 
    } 
} 

如果要限制爲一組語言環境,那麼你將需要一個過濾器,並使用SessionLocaleResolver#setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)方法。

+0

我的解決方案存在問題「Bean屬性」語言環境「不可寫或具有無效的setter方法。」 ...「無效的屬性'locale'的bean類[org.springframework.web.servlet.i18n.FixedLocaleResolver]」 – Rafael 2015-01-13 12:28:13

+1

這似乎工作 - > localResolver(FixedLocaleResolver,Locale.US) – Rafael 2015-01-13 12:32:53

相關問題