从零开始学习SpringBoot我爱编程

SpringBoot - Web开发 国际化

2018-05-15  本文已影响51人  BzCoder

本章开始将围绕实际项目来学习,之后涉及到的学习的资料可以在Bootstrap的示例中找到。
要完成其实很简单,主要按以下步骤:

  1. 编写国际化配置文件
  2. 使用ResourceBundleMessageSource管理国际化资源文件
  3. 在页面取出国际化内容

一.编写国际化配置文件

配置

在开始编写国际化配置文件之前,需要做一个准备工作:
选择File-Other Setting-Default Setting-File Encodings 按照上图配置,防止乱码出现

国际化配置文件

文件名命名规则基础名+语言国家代码+.properties,默认可以不加语言国家代码如xxx.properties, xxx_zh_CN.properties,xxx_en_US.properties,当IDEA检测到你的国际化配置,就会转成上图的国际化视图。

二.管理国际化资源文件

有关ResourceBundleMessageSource配置当然SpringBoot已经帮你完成了,我们查看他对应的自动配置类MessageSourceAutoConfiguration

@Bean
    public MessageSource messageSource() {
        MessageSourceProperties properties = messageSourceProperties();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
                if (StringUtils.hasText(properties.getBasename())) {
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                    StringUtils.trimAllWhitespace(properties.getBasename())));
        }
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }
        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }
public class MessageSourceProperties {

    /**
     * Comma-separated list of basenames (essentially a fully-qualified classpath
     * location), each following the ResourceBundle convention with relaxed support for
     * slash based locations. If it doesn't contain a package qualifier (such as
     * "org.mypackage"), it will be resolved from the classpath root.
     */
    private String basename = "messages";
        //我们的配置文件可以直接放在类路径下叫message.properties,就不需要做任何配置就可以做国际化
    /**
     * Message bundles encoding.
     */

经过查看配置文件得知,假如我们需要使用的自己的国际化配置,需要在配置文件中写入包名

spring.messages.basename=inter.login

三.在页面取出国际化内容

我们继续查看Thymeleaf文档:

也就是Message内容是通过#{...}语句取出的,完成后网页就可以随着浏览器语言环境的变化切换语言了,代码在文章结尾给出。

原理:
国际化Locale(区域信息对象) ;通过LocaleResolver(区域信息解析器)去操作,当然SpringBoot也自动配置了区域信息解析器,看一下代码:

        @Bean
        @ConditionalOnMissingBean
        @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
        public LocaleResolver localeResolver() {
            if (this.mvcProperties
                    .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
                return new FixedLocaleResolver(this.mvcProperties.getLocale());
            }
            AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
            localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
            return localeResolver;

        }

以上代码的逻辑:假如取到固定的WebMvcProperties.LocaleResolver.FIXED就使用固定的,否则就使用AcceptHeaderLocaleResolverAcceptHeaderLocaleResolver作用是根据请求头获取区域信息。

请求头

当我们想在代码中加入语言切换的功能,那么就要添加自己的区域信息解析器。

定义自己的区域信息解析器:

/**
 * @author BaoZhou
 * @date 2018/5/15
 */

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //根据得到参数重新构造locale
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l))
        {
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

添加到容器中:

  @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

网页代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" th:href="@{assets/brand/favicon.ico}">

    <title>Signin Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link th:href="@{dist/css/bootstrap.min.css}" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link th:href="@{assets/css/ie10-viewport-bug-workaround.css}" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link th:href="@{assets/css/signin.css}" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]>
    <script src="../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script th:src="@{assets/js/ie-emulation-modes-warning.js}"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body class="text-center">

<div class="container">

    <form class="form-signin">
        <h2 class="form-signin-heading" th:text="#{login.tip}">Please sign in</h2>
        <label for="inputEmail" class="sr-only" th:text="#{login.username}">Email address</label>
        <input type="email" id="inputEmail" class="form-control" th:placeholder="#{login.username}" required autofocus>
        <label for="inputPassword" class="sr-only" th:text="#{login.password}">Password</label>
        <input type="password" id="inputPassword" class="form-control" th:placeholder="#{login.password}" required>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me" th:text="#{login.remember}">
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
    </form>
    <p class="mt-5 mb-3 text-muted">@2018-2019</p>
    <a btn class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
    <a btn class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</div> <!-- /container -->


<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
运行结果
运行结果

大功告成,十分简单易懂。收工!

上一篇下一篇

猜你喜欢

热点阅读