Java國際化(i18n)

來源:互聯網
上載者:User

標籤:session   請求   nic   資源檔   dea   http   資源   port   處理   

Java國際化(i18n)

最近在做一個網站國際化的功能。用Java做開發,使用spring+velocity.

Java提供了對i18n的支援,spring對其做了整合,可以很方便的配置。主要思想就是根據語言來讀取不同的設定檔,來顯示對應的文本。主要步驟如下:

1. 用兩個properties檔案來儲存“符號”到對應語言的映射。如messages_en.properties和messages_zh.properties, 將其放到工程的classPath下

#messages_en.propertiestitle=service introduction

#messages_cn.properties

title=\u670d\u52a1\u8bf4\u660e

 注意中文要使用unicode編碼

2. 配置spring的xml檔案:

    spring提供了多種國際化的支援方式,如基於瀏覽器,session和cookie等。項目中使用cookie方式

  

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">       <property name="cookieMaxAge" value="604800"/>       <property name="defaultLocale" value="zh_CN"/>       <property name="cookieName" value="lang"/>     </bean>

  聲明1中的資源檔

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">        <property name="basename" value="messages"/>        <property name="useCodeAsDefaultMessage" value="true" />    </bean>

  使用攔截器來處理請求,讓對應的頁面國際化

<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />...<property name="interceptors" ref="localeChangeInterceptor"></property>
...

  或者

<mvc:interceptors><bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /><mvc:interceptor>...</mvc:interceptor></mvc:interceptors>

 

然後在vm頁面中調用預留位置就可以了

#springMessage("title")

3. 另外可以寫一個controller來切換語言

@RequestMapping("/lang")public String lang(    HttpServletRequest request, HttpServletResponse response) throws   Exception {    String langType = request.getParameter("langType");    if ("en".equals(langType)) {        cookieLocaleResolver.setLocale(request, response, Locale.ENGLISH);    } else {        cookieLocaleResolver.setLocale(request, response, Locale.CHINA);    }    return null;}

 

  

Java國際化(i18n)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.