springboot 使用i18n进行国际化

一、i18n介绍html

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

二、页面元素国际化:jquery

  pom文件引入thymeleaf依赖:git

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

  新增一个html文件hello.html:github

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

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

  访问接口springboot

@Controller
public class HelloController {

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

  启动项目访问http://localhost:8080/hello就能够看到效果app

三、修改默认messages配置前缀ide

  上面使用的是messages默认的配置,即直接放在resources/目录下,通常项目中会使用本身的目录存放,如放在resources/i18n/目录下spring-boot

  在application配置中添加

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

  加好以后从新访问便可

四、代码中使用国际化

   //注入 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>

项目启动后点击连接测试效果便可

七、访问乱码问题解决

 见springboot使用i18n乱码

项目源码:github

相关文章
相关标签/搜索