zoukankan      html  css  js  c++  java
  • springboot 使用i18n进行国际化

    1、i18n介绍

      i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。在资讯领域,国际化(i18n)指让产品(出版物,软件,硬件等)无需做大的改变就能够适应不同的语言和地区的需要。对程序来说,在不修改内部代码的情况下,能根据不同语言及地区显示相应的界面。

    2、页面元素国际化:

      pom文件引入thymeleaf依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

      新增一个html文件hello.html:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org"
    <head>
        <title>hello</title>
    </head>
    <body>
        <span>
            <label th:text="#{welcome}"></label>
        </span>
    </body>
    </html>    

      SpringBoot 默认支持国际化的,在resources/下定义国际化文件,名称必须以messages开头,因为 MessageSourceAutoConfiguration 类中指定了前缀。

    messages.properties
    welcome = 欢迎使用i18n(默认)
    messages_zh_CN.properties
    welcome = 欢迎使用i18n(中文)
    messages_en_US.properties
    welcome = welcome to use i18n(english)

      访问接口

    @Controller
    public class HelloController {
    
        @RequestMapping(value = "hello")
        public String hello() {
            return "hello";
        }
    }

      启动项目访问http://localhost:8080/hello就可以看到效果

    3、修改默认messages配置前缀

      上面使用的是messages默认的配置,即直接放在resources/目录下,一般项目中会使用自己的目录存放,如放在resources/i18n/目录下

      在application配置中添加

    #i18n
    spring:
      messages:
        encoding: UTF-8
        basename: i18n/messages

      加好之后重新访问即可

    4、代码中使用国际化

       //注入 MessageSource 对象,通过 getMessage 方法获取信息
        @Autowired
        private MessageSource messageSource;
        
        //使用
        messageSource.getMessage("welcome", null, locale);

    说明:第一个参数是国际化文件的key,第二个参数是key对应value中的占位符数据(如welcome=欢迎使用{0}中的{0}就是占位符,0表示是第一个,对应数据中的第一个值),第三个是当前区域

    5、会话区域解析器SessionLocaleResolver

       注入 Bean

    //注入 Bean,会话区域解析器只针对当前会话有效
    @Bean
    public LocaleResolver localeResolver() {
          SessionLocaleResolver slr = new SessionLocaleResolver();
          //设置默认区域,
          slr.setDefaultLocale(Locale.ENGLISH);
          return slr;
    }

      接口控制器:

       @RequestMapping("/i18n")
        public String changeSessionLanauage(HttpServletRequest request, String lang){
            System.out.println(lang);
            if(CommonConsts.LANG_ZH.equals(lang)){
                //代码中即可通过以下方法进行语言设置
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("zh","CN"));
            }else if(CommonConsts.LANG_EN.equals(lang)){
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("en","US"));
            }
            return "redirect:/hello";
        }

    其中request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("zh","CN"));用于切换当前会话区域

      前端页面hello.html修改:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>hello</title>
        <script th:src="@{js/jquery.min.js}"></script>
        <script th:src="@{js/hello.js}"></script>
    </head>
    <body>
    <p><label th:text="#{welcome}"></label></p><br/>
    <span th:text="#{lang}"></span>
    <select id="locales">
        <option value=""></option>
        <option value="zh" th:text="zh"></option>
        <option value="en" th:text="en"></option>
    </select>
    </body>
    </html>

      hello.js文件

    $(function () {
        $("#locales").change(function() {
            var lang = $("#locales").val();
            if (lang != "") {
                window.location.replace("/i18n?lang=" + lang);
            }
        });
    });

      需要同时作用于Cookie时,修改接口控制器:

        @RequestMapping("/i18n2")
        public String changeSessionLanauage2(HttpServletRequest request, HttpServletResponse response, String lang){
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if(CommonConsts.LANG_ZH.equals(lang)){
                localeResolver.setLocale(request, response, new Locale("zh","CN"));
            }else if(CommonConsts.LANG_EN.equals(lang)){
                localeResolver.setLocale(request, response, new Locale("en","US"));
            }
            return"redirect:/hello";
        }

    6、使用参数进行语言切换

    使用拦截器来拦截请求接口中的参数来实现语言切换

      注入区域切换拦截bean

        @Bean
        public LocaleChangeInterceptor localeChangeInterceptor() {
            LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
         //对请求路径中的参数lang进行拦截
            lci.setParamName("lang");
    
            return lci;
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(localeChangeInterceptor());
        }

      hello.html添加修改:

    点击切换语言:
    <a href="/hello?lang=zh_CN">简体中文</a> &nbsp;&nbsp;
    <a href="/hello?lang=en_US">English(US)</a><br>

    项目启动后点击链接测试效果即可

    7、访问乱码问题解决

     见springboot使用i18n乱码

    项目源码:github

  • 相关阅读:
    OpenStack平台监控脚本-基础版
    制作rpm包,可以免除多次编译安装
    openstack安装指南
    服务器状态持续监控脚本
    搭建OpenStack私有云准备工作
    一键配置openstack-cata版的在线yum源
    openstack的yum源出错,配置openstack-ocata版的在线yum源,openstack的yum源配置
    py小结一
    Windows在cmd界面运行C++程序
    数字三角形「动态规划」
  • 原文地址:https://www.cnblogs.com/kingsonfu/p/10396946.html
Copyright © 2011-2022 走看看