基于springboot的i18n国际化

发布时间:2019-11-07
技术:springboot1.3.3.RELEASE + jdk1.8 + maven3.0.5

概述

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

详细

一、运行效果

image.png

image.png



二、实现过程

①、页面元素国际化

在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 类中指定了前缀。x


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";
    }
}


②、修改默认messages配置前缀

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

如放在resources/i18n/目录下    

在application配置中添加

#设置国际化配置文件存放在classpath:/i18n目录下
spring.messages.basename=i18n/messages
#设置加载资源的缓存失效时间,-1表示永久有效,默认为-1
spring.messages.cache-seconds=3600

③、代码中使用国际化

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

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


④、会话区域解析器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";
    }


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

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

注入区域切换拦截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>


三、项目结构图

image.png


四、补充

i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。在资讯领域,国际化(i18n)指让产品(出版物,软件,硬件等)无需做大的改变就能够适应不同的语言和地区的需要。对程序来说,在不修改内部代码的情况下,能根据不同语言及地区显示相应的界面。 在全球化的时代,国际化尤为重要,因为产品的潜在用户可能来自世界的各个角落。通常与i18n相关的还有L10n(“本地化”的简称)

本实例支付的费用只是购买源码的费用,如有疑问欢迎在文末留言交流,如需作者在线代码指导、定制等,在作者开启付费服务后,可以点击“购买服务”进行实时联系,请知悉,谢谢
手机上随时阅读、收藏该文章 ?请扫下方二维码