本文轉載僅供自己學習收錄,不做任何商業用途,如有需要可訪問原地址:http://blog.csdn.net/qyf_5445/article/details/8124362
如何在spring mvc框架中實現MessageSource來管理國際資源文件呢
如下:
1.在applicationContext.xml文件內配置如下
- <span style="font-size:14px;"><bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
- <property name="defaultEncoding" value="iso-8859-1" />
- <property name="useCodeAsDefaultMessage" value="true" />
- <property name="cacheSeconds" value="10"></property>
- <property name="basenames">
- <list>
- <value>classpath:messages</value>
- </list>
- </property>
- </bean></span>
設置“useCodeAsDefaultMessage”,默認為false,這樣當Spring在ResourceBundle中找不到messageKey的話,就拋出NoSuchMessageException, 把它設置為True,則找不到不會拋出異常,而是使用messageKey作為返回值。
2.在你的src文件路徑下新建 messages.properties文件,里面存寫一些 信息
- <span style="font-size:14px;">mobile.is.null=手機號碼不能為空
- mobile.is.invalid=手機號碼無效
- username.is.null=用戶名不能為空
- username.already.exists=用戶名已經存在</span>
3.在需要的controller里面可以如下:
model.addAttribute("msgs","username.already.exists");
4.用fmt標簽才能正常顯示
<%@ taglib prefix="fmt" uri="http://Java.sun.com/jsp/jstl/fmt" %>
- <c:if test="${msgs!=null && msgs.size()>0}">
- <fmt:message key="${msgs}" />
- </c:if>