Spring MVC在代码中获取国际化信息

        本文基于Spring MVC国际化

        在Spring MVC国际化一文中描述了如何实现Spring的国际化,也描述了在jsp页面中如何获取国际化信息,本文描述如何在java代码中获取国际化信息。

        在Java代码中,获取国际化信息使用org.springframework.web.context.WebApplicationContext的getMessage方法,getMessage方法中需要使用当前的Locale信息,于是,怎样获取国际化信息集中在以下两点:

        1. 如何获取WebApplicationContext?

        2. 如何获取当前使用的Locale?

        首先,如何获取WebApplicationContext呢,很简单,在任何一个类实现org.springframework.web.context.ServletContextAware并重写其setServletContext方法,如下所示:

public class MenuServiceImpl implements MenuService, ServletContextAware {
        private ServletContext servletContext;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.context.ServletContextAware#setServletContext
	 * (javax.servlet.ServletContext)
	 */
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public void test() {
		WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	}
}

        如此,我们取得了WebApplicationContext信息。

        其次,如何获取当前使用的Locale信息?一行代码搞定:

Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
        WebApplicationContext信息和Locale信息都获取到后,再用一行代码获取国际化信息:

String menuName = applicationContext.getMessage("text.menu.name",null, "菜单A", locale);
        在getMessage中有四个变量,依次分别为message_*.properties文件中的key,key中{0}、{1}等对应的值,默认值和Locale。






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值