在web开发中我们常常会遇到国际化语言处理问题,那么如何来做到国际化呢?

你能get的知识点?

  1. 使用springgmvc与thymeleaf进行国际化处理。
  2. 使用springgmvc与jsp进行国际化处理。
  3. 使用springboot与thymeleaf进行国际化处理。

你必须要知道的概念

关于i18n:

i18n(其来源是英文单词

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

在全球化的时代,国际化尤为重要,因为产品的潜在用户可能来自世界的各个角落。通常与i18n相关的还有L10n(“本地化”的简称)。

一:使用springgmvc与thymeleaf进行国际化处理。



1、在项目spring的Spring MVC配置文件springmvc.xml中,你需要配置

  • 资源文件绑定器ResourceBundleMessageSource
  • SessionLocaleResolver(用于将Locale对象存储于Session中供后续使用)
  • LocaleChangeInterceptor(用于获取请求中的locale信息,将其转为Locale对象,获取LocaleResolver对象)。
  1. <!-- 使用ResourceBundleMessageSource实现国际化资源-->
  2. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  3. <property name="basenames" value="messages"/>
  4. <property name="defaultEncoding" value="UTF-8"/>
  5. </bean>
  6. <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  7. <property name="defaultLocale" value="en_US"/>
  8. </bean>
  9. <mvc:interceptors>
  10. <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  11. <property name="paramName" value="lang"/>
  12. </bean>
  13. </mvc:interceptors>

2、在控制器中添加方法localeChange处理国际化,并注入ResourceBundleMessageSource的Bean实例

  1. @Autowired
  2. private ResourceBundleMessageSource messageSource;
  3. @GetMapping("/localeChange")
  4. public String localeChange(Locale locale){
  5. String userName = messageSource.getMessage("userName",null,locale);
  6. String passWord = messageSource.getMessage("passWord",null,locale);
  7. System.out.println(userName+passWord);
  8. return "login";
  9. }

3、创建国际化资源属性文件messages_en_US.propertiesmessages_zh_CN.properties

注意这两个文件的命名格式,否则解析会出错,

并且我这里的两个文件就是位于我的resources目录下,当你新建这两个文件后,他会自动给你归档,不要以为我的这两个上面还有一层,你也跟着建一个文件夹。

  1. 1messages_en_US.properties
  2. userName=userName
  3. passWord=password
  4. 2messages_zh_CN.properties
  5. userName=用户名
  6. passWord=密码

4、新建html,用于最终的显示,这里使用的是thymeleaf模板引擎,没有做springmvc与thymeleaf的整合可以看我的另一篇文章 springmvc与thymeleaf的整合

  1. <!--
  2. @Author: lomtom
  3. @Date: 2020/4/19
  4. @Time: 16:51
  5. @Email: lomtom@qq.com
  6. -->
  7. <!DOCTYPE html>
  8. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  9. <head>
  10. <meta charset="UTF-8">
  11. <title>login</title>
  12. </head>
  13. <body>
  14. <h2 th:text="#{userName}+' '+#{passWord}"></h2>
  15. <a href="localeChange?lang=en_US">英文</a>
  16. <a href="localeChange?lang=zh_CN">中文</a>
  17. </body>
  18. </html>

最终的效果:

二: 使用springgmvc与jsp进行国际化处理。

这里的前三部与上面相同,唯一有区别的就是最终视图的显示,使用jsp,就要用到JSTL标签,这里需要引入JSTL的message标签。

即在头部加入<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

然后通过<spring:message>元素的key属性输出资源属性文件中的key所对应的值,最终的jsp是这样的。

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
  3. <html>
  4. <head>
  5. <title>login</title>
  6. </head>
  7. <body>
  8. <p><spring:message code="userName"/></p>
  9. <p><spring:message code="password"/></p>
  10. <a href="localeChange?lang=en_US">英文</a>
  11. <a href="localeChange?lang=zh_US">中文</a>
  12. </body>
  13. </html>

依次点击“中文”和“英文”链接,可以看到<spring:message>元素显示的文本能够根据所传递的语言来动态展现。

三:使用springboot与thymeleaf进行国际化处理。

没有做springmvc与thymeleaf的整合可以看我的另一篇文章 springmvc与thymeleaf的整合

1、创建配置文件,抽取页面要显示的消息



2、springboot已经配置好了组件,加入即可

  1. spring:
  2. # 让springboot来管理配置文件
  3. messages:
  4. basename: i18n.login

3、让页面获取即可(默认根据浏览器语言来切换),利用thymeleaf

  1. <button type="submit" class="btn btn-default" th:text="#{login.btn}">Sign in</button>

4、根据链接来进行语言的切换

原理:国际化locale(区域信息对象),如果自定义了,就是用自己的,而不是系统的

  1. <a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">[[#{login.zh}]]</a>
  2. <a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">[[#{login.en}]]</a>
  3. <a class="btn btn-sm" th:href="@{/index.html(l=kor_KR)}">[[#{login.kor}]]</a>

5、解析器,因为我们设置了自己的区域信息对象,所以我们需要书写自己的解析器。并且注入到容器中。

  1. 1、新建一个LocaleResolver
  2. public class MyLocaleResolver implements LocaleResolver {
  3. @Override
  4. //解析区域信息
  5. public Locale resolveLocale(HttpServletRequest httpServletRequest) {
  6. String l = httpServletRequest.getParameter("l");
  7. Locale locale = Locale.getDefault();
  8. if(!StringUtils.isEmpty(l)){
  9. String[] split = l.split("_");
  10. locale = new Locale(split[0],split[1]);
  11. }
  12. return locale;
  13. }
  14. @Override
  15. public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
  16. }
  17. }
  18. 2、在config文件中加入到容器中
  19. @Configuration
  20. public class MyMvcConfig implements WebMvcConfigurer {
  21. @Bean
  22. public LocaleResolver localeResolver(){
  23. return new MyLocaleResolver();
  24. }
  25. }

这个写的时间过于久远,所以贴出代码,感兴趣的,可以自己研究研究:



1、html

  1. <!--
  2. User: 欧阳隆桐
  3. Date: 2019/12/22
  4. Time: 16:42
  5. -->
  6. <!DOCTYPE html>
  7. <html lang="ch" xmlns:th="http://www.thymeleaf.org">
  8. <head>
  9. <meta charset="UTF-8">
  10. <title>[[#{login.title}]]</title>
  11. <link rel="stylesheet" href="/webjars/bootstrap/4.4.1/css/bootstrap.css" th:href="@{/webjars/bootstrap/4.4.1/css/bootstrap.css}">
  12. <script src="/webjars/jquery/3.3.1/jquery.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
  13. <script src="/webjars/bootstrap/4.4.1/js/bootstrap.js" th:src="@{/webjars/bootstrap/4.4.1/js/bootstrap.js}"></script>
  14. </head>
  15. <body>
  16. <div class="container">
  17. <div class="row clearfix">
  18. <div class="col-md-12 column">
  19. <form class="form-horizontal" role="form" th:action="@{/user/login}" method="post">
  20. <div class="form-group text-center">
  21. <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
  22. <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  23. </div>
  24. <div class="form-group">
  25. <label for="username" class="col-sm-2 control-label" th:text="#{login.username}">Username</label>
  26. <div class="col-sm-10">
  27. <input type="text" class="form-control" name="username" id="username" />
  28. </div>
  29. </div>
  30. <div class="form-group">
  31. <label for="password" class="col-sm-2 control-label" th:text="#{login.password}">Password</label>
  32. <div class="col-sm-10">
  33. <input type="password" class="form-control" name="password" id="password" />
  34. </div>
  35. </div>
  36. <div class="form-group">
  37. <div class="col-sm-offset-2 col-sm-10">
  38. <div class="checkbox">
  39. <label><input type="checkbox" />[[#{login.remember}]]</label>
  40. </div>
  41. </div>
  42. </div>
  43. <div class="form-group">
  44. <div class="col-sm-offset-2 col-sm-10">
  45. <button type="submit" class="btn btn-default" th:text="#{login.btn}">Sign in</button>
  46. </div>
  47. </div>
  48. <div class="form-group text-center">
  49. <p class="mt-5 mb-3 text-muted">@ 2019</p>
  50. <a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">[[#{login.zh}]]</a>
  51. <a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">[[#{login.en}]]</a>
  52. <a class="btn btn-sm" th:href="@{/index.html(l=kor_KR)}">[[#{login.kor}]]</a>
  53. </div>
  54. </form>
  55. </div>
  56. </div>
  57. </div>
  58. </body>
  59. </html>

2、properties

  1. 1、默认
  2. login.btn=登录
  3. login.en=英文
  4. login.kor=韩文
  5. login.password=密码
  6. login.remember=记住我
  7. login.tip=请登录
  8. login.title=登录
  9. login.username=用户名
  10. login.zh=中文
  11. 2、英文
  12. login.btn=Sign in
  13. login.en=English
  14. login.kor=Korean
  15. login.password=Password
  16. login.remember=Remember me
  17. login.tip=Please sign in
  18. login.title=Login
  19. login.username=Username
  20. login.zh=Chinese
  21. 3、韩文
  22. login.btn=로그인
  23. login.en=영어
  24. login.kor=한글
  25. login.password=암호
  26. login.remember=저를 기억하세요
  27. login.tip=로그인하십시오.
  28. login.title=로그인
  29. login.username=사용자 이름
  30. login.zh=중국어
  31. 4、中文
  32. login.btn=登录
  33. login.en=英文
  34. login.kor=韩文
  35. login.password=密码
  36. login.remember=记住我
  37. login.tip=请登录
  38. login.title=登录
  39. login.username=用户名
  40. login.zh=中文

3、java

  1. 1LocaleResolver
  2. /**
  3. * 可以在连接上携带区域信息
  4. */
  5. public class MyLocaleResolver implements LocaleResolver {
  6. @Override
  7. //解析区域信息
  8. public Locale resolveLocale(HttpServletRequest httpServletRequest) {
  9. String l = httpServletRequest.getParameter("l");
  10. Locale locale = Locale.getDefault();
  11. if(!StringUtils.isEmpty(l)){
  12. String[] split = l.split("_");
  13. locale = new Locale(split[0],split[1]);
  14. }
  15. return locale;
  16. }
  17. @Override
  18. public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
  19. }
  20. }
  21. 2config
  22. @Configuration
  23. public class MyMvcConfig implements WebMvcConfigurer {
  24. @Bean
  25. public LocaleResolver localeResolver(){
  26. return new MyLocaleResolver();
  27. }
  28. }

4、yml

  1. spring:
  2. # 让springboot来管理配置文件
  3. messages:
  4. basename: i18n.login

问题

描述:显示中文时乱码

解决:将国际化资源属性文件的编码格式设置为UTF-8即可,当然也可以把整个项目编码格式都设为UTF-8

【spring 国际化】springMVC、springboot国际化处理详解的更多相关文章

  1. Spring全家桶——SpringBoot之AOP详解

    Spring全家桶--SpringBoot之AOP详解 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关键单元是类,而在AOP中,模块化单元是方 ...

  2. Springboot mini - Solon详解(七)- Solon Ioc 的注解对比Spring及JSR330

    Springboot min -Solon 详解系列文章: Springboot mini - Solon详解(一)- 快速入门 Springboot mini - Solon详解(二)- Solon ...

  3. Spring源码之九finishRefresh详解

    Spring源码之九finishRefresh详解 公众号搜索[程序员田同学],专职程序员兼业余写手,生活不止于写代码 Spring IoC 的核心内容要收尾了,本文将对最后一个方法 finishRe ...

  4. SpringBoot之DispatcherServlet详解及源码解析

    在使用SpringBoot之后,我们表面上已经无法直接看到DispatcherServlet的使用了.本篇文章,带大家从最初DispatcherServlet的使用开始到SpringBoot源码中Di ...

  5. 转:springmvc常用注解标签详解

    Spring5:@Autowired注解.@Resource注解和@Service注解 - IT·达人 - 博客园--这篇顺序渐进,讲得超级好--此人博客很不错http://www.cnblogs.c ...

  6. SpringMVC 之类型转换Converter详解转载

    SpringMVC之类型转换Converter详解 本文转载 http://www.tuicool.com/articles/uUjaum 1.1     目录 1.1      目录 1.2     ...

  7. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(一)配置文件详解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(一)配置文件详解 1.pom.xml ...

  8. Spring Boot源码中模块详解

    Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...

  9. SpringBoot Profile使用详解及配置源码解析

    在实践的过程中我们经常会遇到不同的环境需要不同配置文件的情况,如果每换一个环境重新修改配置文件或重新打包一次会比较麻烦,Spring Boot为此提供了Profile配置来解决此问题. Profile ...

  10. Springboot mini - Solon详解(四)- Solon的事务传播机制

    Springboot min -Solon 详解系列文章: Springboot mini - Solon详解(一)- 快速入门 Springboot mini - Solon详解(二)- Solon ...

随机推荐

  1. Mol Cell Proteomics. | MARMoSET – Extracting Publication-ready Mass Spectrometry Metadata from RAW Files

    本文是马克思普朗克心肺研究所的三名研究者Marina Kiweler.Mario Looso和Johannes Graumann发表在8月刊的MCP的一篇文章. 由于Omics实验经常涉及数百个数据文 ...

  2. 记录一次云主机部署openstack的血泪史

    看见这个部署成功的留下了激动的泪水 经过长时间的BUG苦肝终于成功部署成功  部署的环境2vCPU 8GB 阿里云主机,部署成功以后内存占用确实蛮高的 记录这一次踩坑,给后来者避免踩坑时间,个人踩坑踩 ...

  3. Scapy编写ICMP扫描脚本

    使用Scapy模块编写ICMP扫描脚本: from scapy.all import * import optparse import threading import os def scan(ipt ...

  4. RMQ Tarjan的Sparse-Table算法

    参考博客:https://www.cnblogs.com/wenzhixin/p/9714760.html 预处理时间复杂度是O(nlogn),代码如下: void init(const vector ...

  5. [图中找环] Codeforces 659E New Reform

    New Reform time limit per test 1 second memory limit per test 256 megabytes input standard input out ...

  6. 我是如何用IDEA调试BUG的?

    最近小明的bug有点多,忙的连王者荣耀都顾不上玩了,导致现在不得不抽点时间研究一下作为当前大多Java程序员开发工具的IDEA DEBUG功能,以提高效率. 一.条件断点 场景:我们在遍历某个集合,期 ...

  7. 四、用户交互(输入input,格式化输出)与运算符

    1.接收用户的输入 在Python3:input会将用户输入的所有内容都存成字符串类型 列: username = input("请输入您的账号:") # "egon&q ...

  8. shell脚本中的case条件语句介绍和使用案例

    #前言:这篇我们接着写shell的另外一个条件语句case,上篇讲解了if条件语句.case条件语句我们常用于实现系统服务启动脚本等场景,case条件语句也相当于if条件语句多分支结构,多个选择,ca ...

  9. jmeter响应乱码(十四)

    方法一: jmeter响应乱码解决方法:在jmeter的bin目录下找到jmeter.propertis这个文件,修改里面的#sampleresult.default.encoding=ISO-885 ...

  10. 分布式配置中心Apollo

    1,什么是分布式配置中心 项目中配置文件比较繁杂,而且不同环境的不同配置修改相对频繁,每次发布都需要对应修改配置,如果配置出现错误,需要重新打包发布,时间成本较高,因此需要做统一的分布式注册中心,能做 ...