SpringBoot整合国际化功能

*SpringBoot已经自动配置了管理国际化资源文件的组件

(3)在配置文件中指定国际化资源文件的文件夹及基础文件

 1 #指定国际化资源文件的文件夹及基础文件 2 spring.messages.basename=i18n/index 

添加国际化文件

首先在配置文件 application.yml 填写国际化文件的相对路径,表示读取classpath:/static/i18n/messages_language_country.properties 。例如:

spring:
  messages:
    basename: static/i18n/messages #相对路径 开头请勿添加斜杠

然后在 classpath:/static/i18n 目录中添加如下国际化文件:

默认文件:messages.properties

#这里填写默认翻译,内容可以留空,但文件必须存在。

美式英语:messages_en_US.properties

#这里填写英语翻译。
user.title=User Login
user.welcome=Welcome
user.username=Username
user.password=Password
user.login=Sign In

中文简体:messages_zh_CN.properties

#这里填写中文翻译
user.title=用户登陆
user.welcome=欢迎
user.username=登陆用户
user.password=登陆密码
user.login=登陆

中文繁体:messages_zh_TW.properties

#这里填写繁体翻译
user.title=用戶登陸
user.welcome=歡迎
user.username=登陸用戶
user.password=登陸密碼
user.login=登陸



(4)* 编写自定义的Locale区域解析器

 

 1 package cn.coreqi.config;
 2 
 3 import org.springframework.util.StringUtils;
 4 import org.springframework.web.servlet.LocaleResolver;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.util.Locale;
 9 
10 /**
11  * SpringBoot默认的Locale解析器是根据请求头的区域信息进行解析的(浏览器语言)
12  * 使用自定义的Locale解析器对url的区域信息进行解析达到点击切换区域效果
13  * 一旦我们自定义的区域解析器注册到Spring容器中,则SpringBoot提供的将不自动注册
14  */
15 public class MyLocaleResolver implements LocaleResolver {
16     @Override
17     public Locale resolveLocale(HttpServletRequest httpServletRequest) {
18         String l = httpServletRequest.getParameter("l");
19         if(!StringUtils.isEmpty((l))){
20             String [] s = l.split("_");
21             return new Locale(s[0],s[1]);
22         }
23         return Locale.getDefault();
24     }
25 
26     @Override
27     public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
28 
29     }
30 }

 

(5)注册我们自定义的区域解析器

 

 1 package cn.coreqi.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.servlet.LocaleResolver;
 6 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 7 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 8 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 9 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
10 
11 /**
12  * 扩展SpringMVC
13  * SpringBoot2使用的Spring5,因此将WebMvcConfigurerAdapter改为WebMvcConfigurer
14  * 使用WebMvcConfigurer扩展SpringMVC好处既保留了SpringBoot的自动配置,又能用到我们自己的配置
15  */
16 //@EnableWebMvc //如果我们需要全面接管SpringBoot中的SpringMVC配置则开启此注解,
17                 //开启后,SpringMVC的自动配置将会失效。
18 @Configuration
19 public class WebConfig implements WebMvcConfigurer {
20     @Override
21     public void addViewControllers(ViewControllerRegistry registry) {
22         //设置对“/”的请求映射到index
23         //如果没有数据返回到页面,没有必要用控制器方法对请求进行映射
24         registry.addViewController("/").setViewName("index");
25     }
26 
27     //注册我们自定义的区域解析器,一旦将我们的区域解析器注册到Spring容器中则SpingBoot
28     //默认提供的区域解析器将不会自动注册
29     @Bean
30     public LocaleResolver localeResolver(){
31         return new MyLocaleResolver();
32     }
33 }

 

(6)视图中引用国际化内容

 

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Index首页</title>
 6 </head>
 7 <body>
 8 <h1 th:text="#{username}"></h1>
 9 </body>
10 </html>

 

首先在pom文件引入ThymeleafWeb依赖,然后在页面中只需通过th:xx="#{x.label}"即可获取对应的国际化翻译值。

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

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

例如:

<title th:text="#{user.title}">用户登陆</title>

JS国际化

首先在pom文件引入jQueryjquery-properties-i18n等依赖,然后在初始化后即可通过JS函数获取对应国际化文件的内容。

        <dependency><!--webjars版本定位器 用于省略版本号-->
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>

        <dependency><!--jQuery前端依赖-->
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency><!--jQuery国际化插件-->
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery-i18n-properties</artifactId>
            <version>1.2.7</version>
        </dependency>

例如:为了提高可用性 这里提供了获取当前国际化语言和获取国际化翻译的方法。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="#{user.title}">用户登陆</title>
    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
    <script th:src="@{/webjars/jquery-i18n-properties/jquery.i18n.properties.min.js}"></script>

    <script th:inline="javascript">
        //获取应用路径
        var ROOT = [[${#servletContext.contextPath}]];

        //获取默认语言
        var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];

        //初始化i18n插件
        $.i18n.properties({
            path: ROOT + '/i18n/',//这里表示访问路径
            name: 'messages',//文件名开头
            language: LANG_COUNTRY,//文件名语言 例如en_US
            mode: 'both'//默认值
        });

        //初始化i18n函数
        function i18n(msgKey) {
            try {
                return $.i18n.prop(msgKey);
            } catch (e) {
                return msgKey;
            }
        }

        //获取国际化翻译值
        console.log(i18n('user.title'));
        console.log(i18n('User Login'));
    </script>
</head>
<body>
<div class="logo_box">
    <select id="locale">
        <option value="zh_CN">中文简体</option>
        <option value="zh_TW">中文繁体</option>
        <option value="en_US">English</option>
    </select>
    <h3 th:text="#{user.welcome}">欢迎登陆</h3>

    <form>
        <div class="input_outer">
            <span class="u_user"></span>
            <input id="username" name="username" class="text" type="text" th:placeholder="#{user.username}">
        </div>
        <div class="input_outer">
            <span class="us_uer"></span>
            <input id="password" name="password" class="text" type="password" th:placeholder="#{user.password}">
        </div>
        <div class="mb2">
            <a class="act-but submit" th:text="#{user.login}">登录</a>
        </div>
    </form>
</div>


<script th:inline="javascript">
    //选中语言
    $("#locale").find('option[value="' + LANG_COUNTRY + '"]').attr('selected', true);

    //切换语言
    $("#locale").change(function () {
        $.get(ROOT + '/?lang=' + $("#locale").val(), function () {
            location.reload();
        });
    });

</script>


</body>
</html>

关于i18n插件的更多配置项请查阅 jquery-properties-i18n 官方文档


 

(7)测试

 

出处:https://www.cnblogs.com/fanqisoft/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值