SpringMVC国际化(i18n)(五)

本文介绍了SpringMVC中实现国际化的步骤,包括添加配置文件、改变本地语言、视图层的修改。通过创建不同语言的properties文件,如messages.properties和messages_fr.properties,结合SessionLocaleResolver实现语言切换。在视图层,使用Thymeleaf的EL表达式#{...}引用国际化信息。文章还提供了代码示例和运行效果。

国际化我们通常用缩写来简单,那就是i18n。它就是让我们的系统可以转换成不同的语言。为了转换成不同的言语,我们需要定义不同的文件,如:messages_en.properties,messages_en_US.properties,messages_fr.properties。我想聪明的你,可以看出他们之间的定义格式了。(如果,读者在定义这些文件后,系统没有实现国际化,那么可以将系统默认的语言文件直接用messages.peoperties.)

1. 添加配置文件

接下来,我们要做的事就是转换我们的信息,笔者这里对英语的语言就没有定义为message_en_US.properties文件,而是直接用messages.properties,因为英语就是作为系统的默认语言。messages.properties的配置信息如下:

Size.profileForm.twitterHandle=Please type in your twitter user name
Email.profileForm.email=Please specify a valid email address
NotEmpty.profileForm.email=Please specify your email address
PastLocalDate.profileForm.birthDate=Please specify a real birth date
NotNull.profileForm.birthDate=Please specify your birth date

typeMismatch.birthDate = Invalid birth date format.

NotEmpty.profileForm.tastes=Please enter at least one thing
profile.title=Your profile
twitter.handle=Twitter handle
email=Email
birthdate=Birth Date
tastes.legend=What do you like?
remove=Remove
taste.placeholder=Enter a keyword
add.taste=Add taste
submit=Submit
	

对于法语,读者可以用翻译的软件来翻译。文件是messages_fr.properties

 Email.profileForm.email=Veuillez spécifier une adresse mail valide
NotEmpty.profileForm.email=Veuillez spécifier votre adresse mail
PastLocalDate.profileForm.birthDate=Veuillez donner votre vraie date de naissance
NotNull.profileForm.birthDate=Veuillez spécifier votre date de naissance

typeMismatch.birthDate = Date de naissance invalide.

NotEmpty.profileForm.tastes=Veuillez saisir au moins une chose
profile.title=Votre profil
twitter.handle=Pseudo twitter
email=Email
birthdate=Date de naissance
tastes.legend=Quels sont vos go?ts ?
remove=Supprimer
taste.placeholder=Entrez un mot-clé
add.taste=Ajouter un centre d'intérêt
submit=Envoyer

2.改变本地语言

在我们的程序中,用户使用系统是跟自己本地相关系的。我们会Session中保存用户的个人信息。我们应该要允许用户去改变自己的本地语言。所以我们要使用SessionLocaleResolver.让我们修改WebConfiguration:

package masterSpringMVC.config;

import masterSpringMVC.date.USLocalDateFormatter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.time.LocalDate;
import java.util.Locale;

/**
 * 定制SpringMVC的配置(如:日期、语言等)
 * 有点类似于Spring的xml的文件配置
 * 可以添加需要用的Bean,还有拦截器、事务控制等
 * Created by OwenWilliam on 2016/5/15.
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

    /**
     *格式转换处理
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatterForFieldType(LocalDate.class, new USLocalDateFormatter());
    }

    /**
     * 从HTTP的请求地址中找到所属于的国家
     * @return
     */
    @Bean
    public LocaleResolver localeResolver()

    {
        return new SessionLocaleResolver();
    }

    /**
     * 拦截器:拦截请求的地址
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor()
    {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        //在拦截的地址后面添加?lang=xx。如: http://localhost:8080/profile?lang=fr
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

在上面的代码中,细心的你已经清单到了newSessionLocaleResolver()。其实这个是LocaleResolver的接口。其实LocaleResolver的接口有如下几个:

1)        FixedLocaleResolver: 这修复了配置中定义的区域设置,一旦这个被定义了就不能修改。

2)        CookiesLocaleResolver:这个允许将相关的信息检索和保存到本地的cookie中。

3)        SessionLocaleResolver:这个作用域就是在HTTPsession中。

3.视图层修改

1)        我们需要在视图的profilePage的页面中添加可能更换语言的控件,这个不仅仅是用在这个页面上,同时也是公用部分,所以我们添加到layout的页面。修改之后的页面如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
    <title>Default title</title>
    <link href="/webjars/materializecss/0.96.0/css/materialize.css"
          type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>

    <ul id="lang-dropdown" class="dropdown-content">
        <li><a href="?lang=en_US">English</a></li>
        <li><a href="?lang=fr">French</a></li>
    </ul>
    <nav>
        <div class="nav-wrapper indigo">
            <ul class="right">
                <li>
                    <a class="dropdown-button" href="#!" data-activates="lang-dropdown">
                        <i class="mdi-action-language right"></i>Lang
                    </a>
                </li>
            </ul>
        </div>
    </nav>
    <section layout:fragment="content">
        <p>Page content goes here</p>
    </section>

    <script src="/webjars/jquery/2.1.4/jquery.js"></script>
    <script src="/webjars/materializecss/0.96.0/js/materialize.js"></script>
    <script type="text/javascript">
        $(".dropdown-button").dropdown();
    </script>

    <script type="text/javascript" layout:fragment="script">
    </script>
</body>
</html>

2)        最后,我们要在视图的页面上用到国际化,我们用到的EL表达语言是#{}.

查看下面的代码,清单#{}的地方(profilePage.html)。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout/default">
<head lang="en">
<title>Your profile</title>
</head>
<body>
<div class="row" layout:fragment="content">
<h2 class="indigo-text center" th:text="#{profile.title}">Personal
info</h2>
<form th:action="@{/profile}" th:object="${profileForm}"
method="post" class="col m8 s12 offset-m2">
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.twitterHandle}"
id="twitterHandle" type="text" th:errorclass="invalid"/>
<label for="twitterHandle" th:text="#{twitter.
handle}">Twitter handle</label>
<div th:errors="*{twitterHandle}" class="redtext">Error</div>
</div>
<div class="input-field col s6">
<input th:field="${profileForm.email}" id="email"
type="text" th:errorclass="invalid"/>
<label for="email" th:text="#{email}">Email</label>
<div th:errors="*{email}" class="red-text">Error</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.birthDate}"
id="birthDate" type="text" th:errorclass="invalid"/>
<label for="birthDate" th:text="#{birthdate}" th:place
holder="${dateFormat}">Birth Date</label>
<div th:errors="*{birthDate}" class="red-text">Error</
div>
</div>
</div>
<div class="row s12 center">
<button class="btn indigo waves-effect waves-light"
type="submit" name="save" th:text="#{submit}">Submit
<i class="mdi-content-send right"></i>
</button>
</div>
</form>
</div>
</body>
</html>

4.总结

    在这一章节中,我们学习了SpringMVC的国际化是如何配置的。无非不是messages_xx.properties的文件配置。当然,为了要以通过控件来修改,所以我们在webConfiguration中也添加了代码。这个地方主要是浏览器请求时的地址解析是请求哪一种语言调用。如:http://localhost:8080/profile?lang=fr

。最后,我们也不要忘记在视图层中加入我们国际化文件信息。最后运行的结果如下:


源码路径:git@github.com:owenwilliam/masterSpringMVC.git






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值