spring 国际化配置

在src目录下面加入:

messageResource_zh_CN.properties

messageResource_zh_HK.properties

messageResource_zh_TW.properties



然后在applicationContext.xml中配置

	 <!-- 国际化配置 -->
     <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
     	<property name="basenames">
     		<list>
     			<value>classpath:messageResource</value>
     		</list>
     	</property>
     </bean>
	



那么,在项目中就可以使用

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(req().getSession().getServletContext()); 

String msg  = context.getMessage(  "key" , null , req().getLocale() );


 其中context.getMessage方法,第一个参数为key ,第二个参数为一个数组,用来替换在资源文件中的占位符。第三个参数为Locale信息。

如果要根据当前用户的Locale信息获取国际化字符串,那么就要用到request对象,通过request.getLocale()方法,就能够得到当前用户的Locale信息。

如果是使用struts2,可以通过ServletActionContext.getRequest().getLocale()得到Locale对象。






自定义获取国际化资源的标签,在jsp页面中使用

package com.tuanfang.util.diytag;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.tuanfang.util.SystemUtil;

/**
 * 获取国际化信息标签
 * @author zhoufeng
 *
 */
public class I18NMessage extends BodyTagSupport{

	/**
	 * 消息的key
	 */
	private String key ;
	

	/**
	 * 该字段为可选的。
	 * 如为空,就按照当前用户浏览器的Locale进行获取   
	 * 格式为:zh_CN      en_US
	 */
	private String locale ;


	@Override
	public int doStartTag() throws JspException {
		Locale loc = null ;
		if(locale != null){
			String  ss[] = locale.split("_");
			if(ss.length == 2){
				loc = new Locale(ss[0],ss[1]);
			}
		}
		String msg =  SystemUtil.obtainI18nMessage(key , loc);
		try {
			pageContext.getOut().print(msg);
		} catch (IOException e) {
			e.printStackTrace();  
		}
		return BodyTagSupport.SKIP_BODY; 
	}


	@Override 
	public int doEndTag() throws JspException {
		return BodyTagSupport.EVAL_PAGE ;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	public String getLocale() {
		return locale;
	}


	public void setLocale(String locale) {
		this.locale = locale;
	}


}

	
	<tag>
		<name>i18n</name>
		<tag-class>com.tuanfang.util.diytag.I18NMessage</tag-class>
		<body-content>JSP</body-content>
		<attribute>
			<name>key</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
			<type>java.lang.String</type>
		</attribute>
		<attribute>
			<name>locale</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
			<type>java.lang.String</type>
		</attribute>
	</tag>


<tf:i18n key="helloworld"  locale="zh_TW"/>  


<tf:i18n key="helloworld" />      

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值