spring 国际化配置

一、在spring的配置文件中配置

   <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	    <property name="basename" value="messages"/>  
    </bean>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>  
    


其中的value就是资源文件的名字,我用的value="messages",会自动查找“messages_zh_CN”和“messages_en_US”等文件

二、在后台获取国际化文件的属性值

messages_en_US.properties

title=hello
hello2.str1=How are you! {0},today is {1}

 

messages_zh_CN.properties

title=\u4F60\u597D
hello2.str1 = \u4F60\u597D,{0},\u4ECA\u5929\u662F{1}


第一种方法:通过ResourceBundel获取对应的字符串

@RequestMapping("hello2.do")
	public String hello2(HttpServletRequest req,HttpServletResponse res,ModelMap map){
		ResourceBundle rb1 = ResourceBundle.getBundle("messages",Locale.CHINA);
		ResourceBundle rb2 = ResourceBundle.getBundle("messages",Locale.US);
		
		String str1 = rb1.getString("hello2.str1");
		String str2 = rb2.getString("hello2.str1");
		Object[] param = {"张三",new GregorianCalendar().getTime()};
		str1= new MessageFormat(str1,Locale.CHINA).format(param);
		str2= new MessageFormat(str2,Locale.US).format(param);
		
		map.put("str1", str1);
		map.put("str2", str2);
		
		
		return "hello2";
	}


第二种方法:通过ResourceBundleMessageSource获取

@RequestMapping("hello3.do")
	public String hello3(HttpServletRequest req,HttpServletResponse res,ModelMap map){
		
		Object[] param = {"李四",new GregorianCalendar().getTime()};
		MessageSource ms = new ResourceBundleMessageSource();
		String str2 = ms.getMessage("messages", param, ResourceBundle.getBundle("messages",Locale.US).getString("hello2.str1"), Locale.US);
			
		System.out.println(str2);

		map.put("str2", str2);
		
		
		return "hello3";
	}
	

三、在jsp页面获取属性值

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="lib/spring.tld"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试国家化</title>
</head>
<body>
	<spring:message code="title" /><br>  
	<spring:message code="hello2.str1" arguments="mm,ll" /><br>  
	 <input type="button" value="<spring:message code="title" />"/><br>  
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值