Spring MVC 前后台国际化设置

3 篇文章 0 订阅
2 篇文章 0 订阅

使用Spring MVC 配置国际化,用户可以选择语言,前台后台获取国际化资源的方法:

config :

spring-mvc.xml

<!-- 国际化 -->

	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	    <!-- 国际化信息所在的文件名 -->                     
	    <property name="basename" value="messages" />   
	    <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称  -->               
	    <property name="useCodeAsDefaultMessage" value="true" />           
	</bean>
	

	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
		<property name="defaultLocale" value="en" />
	</bean>
	

jsp:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:message code="key" />

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:message key="key" />

后台方式:

在方法里面: 

RequestContext context = new RequestContext(request);
String message = context.getMessage("key");

或者使用

//使用 LocaleContextHolder.getLocale() 获取当前语言

//使用类 继承 ApplicationContextAware 接口,获取到 ApplicationContext 对象
//获取国际化资源文件对象
Map<String, MessageSource> map =ApplicationContext.getBeansOfType(MessageSource.class) 
//可以获取对应的
String value = MessageSource.getMessage(code,  args, LocaleContextHolder.getLocale()); 

用户修改 语言(以下两种均可):

1.配置controller,

在对应的方法里面:

首先 构造一个 Locale 对象,使用 Locale里面的属性,或者 new Locale(String language, String country),

然后使用:

RequestContext context = new RequestContext(request);
context.changeLocale(Locale locale);

//或者 
LocaleContextHolder.setLocale(Locale locale);

2.配置

<bean id="changeLocale" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
  <property name="interceptors">
   <list>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
   </list>
  </property>
 </bean>

然后 访问controller 的路径为:

<a href="/sys/test?locale=zh_CN">中文</a>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值