SpringMVC国际化

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

1. 添加配置文件

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

[html]  view plain  copy
  1. Size.profileForm.twitterHandle=Please type in your twitter user name  
  2. Email.profileForm.email=Please specify a valid email address  
  3. NotEmpty.profileForm.email=Please specify your email address  
  4. PastLocalDate.profileForm.birthDate=Please specify a real birth date  
  5. NotNull.profileForm.birthDate=Please specify your birth date  
  6.   
  7. typeMismatch.birthDate = Invalid birth date format.  
  8.   
  9. NotEmpty.profileForm.tastes=Please enter at least one thing  
  10. profile.title=Your profile  
  11. twitter.handle=Twitter handle  
  12. email=Email  
  13. birthdate=Birth Date  
  14. tastes.legend=What do you like?  
  15. remove=Remove  
  16. taste.placeholder=Enter a keyword  
  17. add.taste=Add taste  
  18. submit=Submit  
  19.       

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

[html]  view plain  copy
  1.  Email.profileForm.email=Veuillez spécifier une adresse mail valide  
  2. NotEmpty.profileForm.email=Veuillez spécifier votre adresse mail  
  3. PastLocalDate.profileForm.birthDate=Veuillez donner votre vraie date de naissance  
  4. NotNull.profileForm.birthDate=Veuillez spécifier votre date de naissance  
  5.   
  6. typeMismatch.birthDate = Date de naissance invalide.  
  7.   
  8. NotEmpty.profileForm.tastes=Veuillez saisir au moins une chose  
  9. profile.title=Votre profil  
  10. twitter.handle=Pseudo twitter  
  11. email=Email  
  12. birthdate=Date de naissance  
  13. tastes.legend=Quels sont vos go?ts ?  
  14. remove=Supprimer  
  15. taste.placeholder=Entrez un mot-clé  
  16. add.taste=Ajouter un centre d'intérêt  
  17. submit=Envoyer  

2.改变本地语言

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

[java]  view plain  copy
  1. package masterSpringMVC.config;  
  2.   
  3. import masterSpringMVC.date.USLocalDateFormatter;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.format.FormatterRegistry;  
  7. import org.springframework.web.servlet.LocaleResolver;  
  8. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;  
  9. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  10. import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;  
  11. import org.springframework.web.servlet.i18n.SessionLocaleResolver;  
  12.   
  13. import java.time.LocalDate;  
  14. import java.util.Locale;  
  15.   
  16. /** 
  17.  * 定制SpringMVC的配置(如:日期、语言等) 
  18.  * 有点类似于Spring的xml的文件配置 
  19.  * 可以添加需要用的Bean,还有拦截器、事务控制等 
  20.  * Created by OwenWilliam on 2016/5/15. 
  21.  */  
  22. @Configuration  
  23. public class WebConfiguration extends WebMvcConfigurerAdapter {  
  24.   
  25.     /** 
  26.      *格式转换处理 
  27.      * @param registry 
  28.      */  
  29.     @Override  
  30.     public void addFormatters(FormatterRegistry registry) {  
  31.         registry.addFormatterForFieldType(LocalDate.classnew USLocalDateFormatter());  
  32.     }  
  33.   
  34.     /** 
  35.      * 从HTTP的请求地址中找到所属于的国家 
  36.      * @return 
  37.      */  
  38.     @Bean  
  39.     public LocaleResolver localeResolver()  
  40.   
  41.     {  
  42.         return new SessionLocaleResolver();  
  43.     }  
  44.   
  45.     /** 
  46.      * 拦截器:拦截请求的地址 
  47.      * @return 
  48.      */  
  49.     @Bean  
  50.     public LocaleChangeInterceptor localeChangeInterceptor()  
  51.     {  
  52.         LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();  
  53.         //在拦截的地址后面添加?lang=xx。如: http://localhost:8080/profile?lang=fr  
  54.         localeChangeInterceptor.setParamName("lang");  
  55.         return localeChangeInterceptor;  
  56.     }  
  57.   
  58.     /** 
  59.      * 注册拦截器 
  60.      * @param registry 
  61.      */  
  62.     @Override  
  63.     public void addInterceptors(InterceptorRegistry registry) {  
  64.         registry.addInterceptor(localeChangeInterceptor());  
  65.     }  
  66. }  

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

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

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

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

3.视图层修改

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

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org"  
  3.       xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">  
  4. <head>  
  5.     <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>  
  7.     <title>Default title</title>  
  8.     <link href="/webjars/materializecss/0.96.0/css/materialize.css"  
  9.           type="text/css" rel="stylesheet" media="screen,projection"/>  
  10. </head>  
  11. <body>  
  12.   
  13.     <ul id="lang-dropdown" class="dropdown-content">  
  14.         <li><a href="?lang=en_US">English</a></li>  
  15.         <li><a href="?lang=fr">French</a></li>  
  16.     </ul>  
  17.     <nav>  
  18.         <div class="nav-wrapper indigo">  
  19.             <ul class="right">  
  20.                 <li>  
  21.                     <a class="dropdown-button" href="#!" data-activates="lang-dropdown">  
  22.                         <i class="mdi-action-language right"></i>Lang  
  23.                     </a>  
  24.                 </li>  
  25.             </ul>  
  26.         </div>  
  27.     </nav>  
  28.     <section layout:fragment="content">  
  29.         <p>Page content goes here</p>  
  30.     </section>  
  31.   
  32.     <script src="/webjars/jquery/2.1.4/jquery.js"></script>  
  33.     <script src="/webjars/materializecss/0.96.0/js/materialize.js"></script>  
  34.     <script type="text/javascript">  
  35.         $(".dropdown-button").dropdown();  
  36.     </script>  
  37.   
  38.     <script type="text/javascript" layout:fragment="script">  
  39.     </script>  
  40. </body>  
  41. </html>  

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

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

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org"  
  3. xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"  
  4. layout:decorator="layout/default">  
  5. <head lang="en">  
  6. <title>Your profile</title>  
  7. </head>  
  8. <body>  
  9. <div class="row" layout:fragment="content">  
  10. <h2 class="indigo-text center" th:text="#{profile.title}">Personal  
  11. info</h2>  
  12. <form th:action="@{/profile}" th:object="${profileForm}"  
  13. method="post" class="col m8 s12 offset-m2">  
  14. <div class="row">  
  15. <div class="input-field col s6">  
  16. <input th:field="${profileForm.twitterHandle}"  
  17. id="twitterHandle" type="text" th:errorclass="invalid"/>  
  18. <label for="twitterHandle" th:text="#{twitter.  
  19. handle}">Twitter handle</label>  
  20. <div th:errors="*{twitterHandle}" class="redtext">Error</div>  
  21. </div>  
  22. <div class="input-field col s6">  
  23. <input th:field="${profileForm.email}" id="email"  
  24. type="text" th:errorclass="invalid"/>  
  25. <label for="email" th:text="#{email}">Email</label>  
  26. <div th:errors="*{email}" class="red-text">Error</div>  
  27. </div>  
  28. </div>  
  29. <div class="row">  
  30. <div class="input-field col s6">  
  31. <input th:field="${profileForm.birthDate}"  
  32. id="birthDate" type="text" th:errorclass="invalid"/>  
  33. <label for="birthDate" th:text="#{birthdate}" th:place  
  34. holder="${dateFormat}">Birth Date</label>  
  35. <div th:errors="*{birthDate}" class="red-text">Error</  
  36. div>  
  37. </div>  
  38. </div>  
  39. <div class="row s12 center">  
  40. <button class="btn indigo waves-effect waves-light"  
  41. type="submit" name="save" th:text="#{submit}">Submit  
  42. <i class="mdi-content-send right"></i>  
  43. </button>  
  44. </div>  
  45. </form>  
  46. </div>  
  47. </body>  
  48. </html>  

4.总结

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

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


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值