2011-03-21 90 views
1

我有以下形式。如何從Spring MVC獲取當前使用的語言環境?

<form id="langForm" action="" method="get"> 
    <select name="lang" id="lang" class="styled" onchange="this.form.submit();"> 
     <option value="pl" ${param.lang == 'pl' ? 'selected' : ''} >PL</option> 
     <option value="en" ${param.lang == 'en' ? 'selected' : ''} >EN</option> 
    </select> 
</form> 

Spring MVC設置語言參數並關心i18n/l10n。我想更改${param.lang}以讓它通過Spring MVC從會話中獲取當前用戶語言,因爲lang參數不一定出現在每個請求中。我怎樣才能做到這一點?

+5

如果它的響應頭,你爲什麼要* *獲得在servlet的價值? – skaffman 2011-03-21 12:21:57

+0

讓看到我更新 – user6778654 2011-03-21 12:43:34

+2

你」重新使用一些i18n/l10n的框架必須從框架請求它,而不是從HTTP/Servlet請求。只要你不知道你用於i18n/l10n的框架,就不可能給出詳細的答案。 – BalusC 2011-03-21 12:59:57

回答

1

添加休耕在你的XML配置:

... 

<mvc:interceptors> 
     <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" /> 
     <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" 
      p:paramName="lang" /> 
    </mvc:interceptors> 

<bean id="messageSource" 
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basename" value="classpath:messages" /> 
     <property name="defaultEncoding" value="UTF-8" /> 
    </bean> 
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" 
     id="localeResolver" p:cookieName="locale" /> 
... 

通過替換您的代碼:

<form id="langForm" action="" method="get"> 
    <select name="lang" id="lang" class="styled" onchange="this.form.submit();"> 
     <option value="pl">PL</option> 
     <option value="en">EN</option> 
    </select> 
</form> 

在這種配置中選擇的區域時便會保存在cookie中的瀏覽器。

不要忘了在文件中標記的開始命名空間: 的xmlns:MVC = 「http://www.springframework.org/schema/mvc」 和

XSI:的schemaLocation =「HTTP: //www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

教程here

相關問題