springmvc学习笔记(13)——国际化资源文件

                       

为什么要配置国际化资源文件

当我们所做的网站,有可能被外国人访问,或者被浏览器语言为英语的用户访问时,我们就需要配置国际化资源文件。配置之后,可以根据浏览器的语言(中文或英文),自动显示对应的语言。
先来看看配置后的效果:
这里我们使用IE浏览器,一般情况下的显示界面如下
这里写图片描述
然后点击工具->Internet选项->语言
这里写图片描述
点击添加,加入英语(美国)[en-US],点击上移,将其移动到第一行(截图中还未上移),点击确定
刷新页面,发现中文变成了英文
这里写图片描述

如何配置国际化资源文件

1.在src目录下创建三个properties文件
这里写图片描述
截图中第一个文件和第三个文件内容一致
这里写图片描述
第二个文件中,则使用中文
这里写图片描述
(当你输入中文时,会被自动编码成如图所示的内容)

2.在springmvc配置文件中加入bean

<!-- 配置国际化资源文件 --><bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">        <property name="basename" value="i18n"></property>  </bean>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

3.在jsp中加上标签

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

3.你想要国际化的内容处使用fmt标签

    <fmt:message key="i18n.username"></fmt:message>    <br><br>    <fmt:message key="i18n.password"></fmt:message>    <br><br>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

搞定!

后端也可以得到资源文件的值

在上面的例子中,前端根据浏览器的语言也显示不同的语言,其实同时在后端也能得到你要显示的值

看代码

    @Autowired    ResourceBundleMessageSource messagesource;    @RequestMapping("/hello")    public String hello(Locale locale){        String msg = messagesource.getMessage("i18n.password", null, locale);        System.out.println(msg);        return "hello";    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
 
     
  • 我们需要注入一个ResourceBundleMessageSource 的实例。你应该发现了,它就是我们在springmvc配置文件中配置的那个bean
  •  
  • 在目标方法参数中加入Locale
  •  

切换浏览器语言,在控制台打印出以下结果
这里写图片描述

使用超链接切换语言

上面我们都是修改浏览器语言来切换,现在我们实现使用超链接来切换语言

首先,我们要在springmvc配置文件中配置

        <!-- 配置 SessionLocalResolver -->    <bean id="localeResolver"        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">    </bean>        <!-- 拦截器 -->    <mvc:interceptors>        <!-- 配置 LocaleChanceInterceptor -->        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>    </mvc:interceptors>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

然后,在我们的页面中加入两个超链接

    <fmt:message key="i18n.username"></fmt:message>    <br><br>    <fmt:message key="i18n.password"></fmt:message>    <br><br>    <a href="hello?locale=zh_CN">中文</a>    <a href="hello?locale=en_US">english</a>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在页面中,点击中文
这里写图片描述

点击english
这里写图片描述

运行原理/流程

该图来自尚硅谷
这里写图片描述

备注

要使用的jar包有 jstl.jarstandard.jar

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43678306/article/details/86170064