Spring mvc的國際化顯示


1. 首先我們需要在springmvc的配置文件裏做添加一個bean:


<!-- 	國際化消息 -->
 	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>classpath:message</value>
			</list>
		</property>
		 <property name="defaultEncoding" value="UTF-8"/>
 	</bean>

這裏用的org.springframework.context.support.ReloadableResourceBundleMessageSource  還有org.springframework.context.support.ResourceBundleMessageSource,這裏兩者最明顯的區別就是ReloadableResourceBundleMessageSource可以設置編碼,而ResourceBundleMessageSource不可以。


2. 再classpath目錄下新建一個message.properties


3. 接下來我們就可以直接獲取message了,這裏寫了一個工具類:

package com.xiatianlong.controller;

import java.util.Date;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.xiatianlong.DateEditor;

/**
 * 基類Controller
 * @author lolli
 *
 */
public class BaseController {

	@Autowired
	protected MessageSource messageSource;
	
	/**
	 * single message
	 * @param messageKey 
	 * 			message key
	 * @return
	 */
	protected String getMessage(String messageKey) {
		return messageSource.getMessage(messageKey, null, Locale.CHINA);
	}

	/**
	 * has param message
	 * @param messageKey
	 * 			message key
	 * @param args
	 * 			message param array
	 * @return
	 */
	protected String getMessage(String messageKey, Object[] args) {
		return messageSource.getMessage(messageKey, args, Locale.CHINA);
	}
}


4. 使用

@RequestMapping(value = "/article", method = RequestMethod.GET)
	public String publishArticle(Model model){
		
		model.addAttribute("testMessage", getMessage("spring.mvc.text.message"));
		model.addAttribute("testMessageParam", getMessage("spring.mvc.text.message.parm", new Object[]{"test"}));
		
		return "/admin/publishArticle";
	}






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