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不可以。
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);
}
}
@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";
}