SpringBoot support rapid internationalization i18n

learning target

  • How to quickly learn the international language support in the project.

Quick View

Thematic read: "SpringBoot sermon series"

Download Source: springboot-locale-i18n

— Hey Man,Don't forget to Star or Fork . —

Project structure:

 
 

Tutorial

First, the international background

1, the configuration parameters internationalization

The default parser: LocaleResolverused to set the default international language of the current session.

Default interceptors: LocaleChangeInterceptorthe specified parameter name to switch international language. For example, ?lang=zh_CNit means to read international documents messages_zh_CN.properties.

/**
 * 配置国际化语言
 */
@Configuration
public class LocaleConfig { /** * 默认解析器 其中locale表示默认语言 */ @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(Locale.US); return localeResolver; } /** * 默认拦截器 其中lang表示切换语言的参数名 */ @Bean public WebMvcConfigurer localeInterceptor() { return new WebMvcConfigurer() { @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor(); localeInterceptor.setParamName("lang"); registry.addInterceptor(localeInterceptor); } }; } } 

2, add internationalization files

First, the configuration file application.ymlto fill in an international document relative path for read classpath:/static/i18n/messages_language_country.properties. E.g:

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

And then in the classpath:/static/i18ndirectory, add the following international documents:

The default file:messages.properties

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

American English:messages_en_US.properties

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

Chinese Simplified:messages_zh_CN.properties

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

traditional Chinese:messages_zh_TW.properties

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

3, international codes

By static methods of tools MessageUtils.get("user.title")to quickly obtain the translated value of the current international.


/**
 * 国际化工具类
 */
@Component
public class MessageUtils{ private static MessageSource messageSource; public MessageUtils(MessageSource messageSource) { FastLocale.messageSource = messageSource; } /** * 获取单个国际化翻译值 */ public static String get(String msgKey) { try { return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale()); } catch (Exception e) { return msgKey; } } 

Second, the international page

First introduced in the pom file Thymeleafand Webdependence, then the page simply by th:xx="#{x.label}"acquiring an international value corresponding to the translation.

        <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> 

E.g:

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

Three, JS international

Pom file is first introduced jQuery, jquery-properties-i18nand so dependent, and can acquire content corresponding to the file by the international JS function after initialization.

        <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> 

For example: In order to increase the availability provides a method to get the current international language and access to international translation here.

<!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> 

More about i18n plugin configuration items please refer to jquery-properties-i18n official documents .

Fourth, the language switch

Many newcomers do not know how to switch an international language, it is actually very simple Once configured, because the front has been configured interceptor LocaleChangeInterceptor, at this time we only need to attach language parameter in any request langcan, of course, to quickly switch through AJAX.

For example:
the default English: http://http://127.0.0.1:8080?lang=en_US
Chinese Simplified: http://http://127.0.0.1:8080?lang=zh_CN
Chinese Traditional:http://http://127.0.0.1:8080?lang=zh_TW

Fifth, project presentations

English interface

 
 

Chinese interface

 
 

A nice framework everywhere, and efficient integration of better than one of concern, attention SpringBoot, make Java programming easier! !



Author: yizhiwazi
link: https: //www.jianshu.com/p/e2eae08f3255
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin www.cnblogs.com/weizhxa/p/11005819.html