項目整理:springmvc國際化配置messageSource(以中英文爲例)

最近有時間,就整理整理自己做過的項目~

話不多說,一共四步。

1. 編寫語言源配置文件
注意在resources的language下,以“首頁”的中英文替換爲例(注意命名爲navigation.home,第三步會用到)
英文配置
中文配置

2. 設置locale處理器及 messageSource配置
在spring-mvc.xml下添加如下配置(注意localeChangeInterceptor攔截器的value爲lang,第四步要用):

<bean id="messageSource"
	class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<!-- 表示多語言配置文件在根路徑下,以language開頭的文件 -->
		<property name="basename" value="classpath:language/language" />
		<property name="useCodeAsDefaultMessage" value="true" />
	</bean>
	
	<mvc:interceptors>
		<bean id="localeChangeInterceptor"
		class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="lang" />
		</bean>
	</mvc:interceptors>

3. 替換頁面文本爲spring message標籤
爲了識別下面用到的sping標籤,先在jsp中加上

 <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

然後國際化替換文本替換頁面文本爲spring message標籤
就是下面這一行代碼(正如第一步說的navigation.home,code爲即爲它,text爲默認)

<spring:message code="navigation.home" text="首頁"/>
  1. 點擊實現中英文切換(正如第二步所說,注意攔截的參數名爲“lang”)
        <li class="dropdown">
		  <a href="#" class="dropdown-toggle" data-toggle="dropdown"  data-hover="dropdown" data-close-others="true">
		              <span><spring:message code="language.choose" text="語言選擇"/></span>
          <i class="icon-angle-down"></i>
          </a>
          <ul class="dropdown-menu">
            <li><a href="?lang=zh_CN"> 中文</a></li>//注意這兩行
            <li><a href="?lang=en_US"> English</a></li>//注意這兩行
          </ul>
        </li>

效果圖:

在這裏插入圖片描述
在這裏插入圖片描述

關於這個,有任何問題可以留言問我(๑•ᴗ•๑)~

覺得還不錯可以點個贊哦~ 謝謝(๑•ᴗ•๑)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章