项目整理:史上最简单的springmvc国际化配置messageSource(以中英文为例)!!!

最近有时间,就整理整理自己做过的项目~

话不多说,一共四步。

1. 编写语言源配置文件
注意在resources的language下,以“首页”的中英文替换为例(注意命名为navigation.home,第三步会用到)
英文配置
中文配置

2. 设置locale处理器及 messageSource配置
在spring-mvc.xml下添加如下配置(注意localeChangeInterceptor拦截器的value为lang,第四步要用):

<bean id="messageSource"
	class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<!-- 表示多语言配置文件在根路径下,以language开头的文件 -->
		<property name="basename" value="classpath:language/language" />
		<property name="useCodeAsDefaultMessage" value="true" />
	</bean>
	
	<mvc:interceptors>
		<bean id="localeChangeInterceptor"
		class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="lang" />
		</bean>
	</mvc:interceptors>

3. 替换页面文本为spring message标签
为了识别下面用到的sping标签,先在jsp中加上

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

然后国际化替换文本替换页面文本为spring message标签
就是下面这一行代码(正如第一步说的navigation.home,code为即为它,text为默认)

<spring:message code="navigation.home" text="首页"/>
  1. 点击实现中英文切换(正如第二步所说,注意拦截的参数名为“lang”)
        <li class="dropdown">
		  <a href="#" class="dropdown-toggle" data-toggle="dropdown"  data-hover="dropdown" data-close-others="true">
		              <span><spring:message code="language.choose" text="语言选择"/></span>
          <i class="icon-angle-down"></i>
          </a>
          <ul class="dropdown-menu">
            <li><a href="?lang=zh_CN"> 中文</a></li>//注意这两行
            <li><a href="?lang=en_US"> English</a></li>//注意这两行
          </ul>
        </li>

效果图:

在这里插入图片描述
在这里插入图片描述

关于这个,有任何问题可以留言问我(๑•ᴗ•๑)~

觉得还不错可以点个赞哦~ 谢谢(๑•ᴗ•๑)

发布了52 篇原创文章 · 获赞 84 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39380155/article/details/97394230