百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

SpringBoot国际化实现实战,实现语言的自由切换

zhezhongyun 2024-12-29 07:15 51 浏览

国际化是每个大型公司官网或者技术文档都会有的,比如前端UI库element、阿里云等,本节我们利用thymeleaf来实现国际化操作。

青锋开源项目地址

Gitee: https://gitee.com/msxy/qingfeng

关注青锋:获得更多技术支持和开源资料


1.1 新建项目

为了方便后续阅读我们新建模块fw-springboot-international,基本的SpringBoot+thymeleaf+国际化信息(message.properties)项目

1.2 maven配置

添加thymeleaf依赖

<dependencies>
    <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>
    <dependency>
        <groupId>com.yisu.cloud</groupId>
        <artifactId>fw-cloud-common</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

1.3 国际化配置

设置了一个localeResolver,可以采用Cookie来控制国际化的语言,也可以采用Session来控制,两个启用一个即可。还设置一个LocaleChangeInterceptor拦截器来拦截国际化语言的变化,并且将拦截器加入到Spring中。

/**
 * 配置信息
 * @Author xuyisu
 * @Date 2019/12/6
 */
@Configuration
public class I18nConfig extends WebMvcConfigurationSupport {
    /**
     * session区域解析器
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.CHINA);

        return resolver;
    }


    /**
     * cookie区域解析器
     * @return
     */
//    @Bean
//    public LocaleResolver localeResolver() {
//        CookieLocaleResolver slr = new CookieLocaleResolver();
//        //设置默认区域,
//        slr.setDefaultLocale(Locale.CHINA);
//        slr.setCookieMaxAge(3600);//设置cookie有效期.
//        return slr;
//    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 设置请求地址的参数,默认为:locale
//        lci.setParamName(LocaleChangeInterceptor.DEFAULT_PARAM_NAME);
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

1.4 控制层

对于使用thymeleaf的我们可以直接跳转到页面,使用方式和JSP类似。这里我们设置默认页面就是跳转到index.html

/**
 * 首页
 * @Author xuyisu
 * @Date 2019/12/6
 */
@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "/index";
    }
}

1.5 message 信息

中文zh_CN

login.userId=用户名
login.noUserId=请输入用户名
login.password=密码
login.noPassword=密码不能为空
login.login=登录

英文en_US

login.userId = Login ID
login.noUserId = Please enter the user ID
login.password = Password
login.noPassword = password can not be blank
login.login = Login

1.6 页面

模拟一个简单的表单登录

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>SpringBoot-international</title>
</head>
<body>
<div>
    <form th:align="center">
        <label  th:text="#{login.userId}">Username</label>
        <input type="text"  th:placeholder="#{login.noUserId}" required="" autofocus="">
        <br>
        <label th:text="#{login.password}">Password</label>
        <input type="password"  th:placeholder="#{login.noPassword}" required="">
        <br>
        <button  type="submit" th:text="#{login.login}">Sign in</button>
    </form>
</div>
</body>
</html>

1.7 应用启动并访问

浏览器输入http://localhost:8774/,可以看到如下表单,默认是中文的,所以他默认会去messages_zh_CN.properties中找,如果没有就会去messages.properties中找。


如果输入http://localhost:8774/?locale=en_US语言就会切到英文。同样的如果url后参数设置为
locale=zh_CH,语言就会切到中文

1.8 前后端分离的情况

对于如果不是thymeleaf的环境,而是前后端分离的情况,可以使用如下方式,通过接口设置语言环境,默认中文,然后通过key 获取对应的value值。

/**
 * 设置语言环境
 * @Author xuyisu
 * @Date 2019/12/6
 */
@RestController
public class LanguageController {


    @Autowired
    private MessageUtil messageUtil;


    /**
     * 设置语言
     * @param request
     * @param response
     * @param lang
     * @return
     */
    @GetMapping("/setLang")
    public FwResult getInfoByLang(HttpServletRequest request, HttpServletResponse response,
                                  String lang){
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if("zh".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("zh", "CN"));
        }else if("en".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("en", "US"));
        }
        return FwResult.okMsg("设置"+lang+"成功");
    }


    /**
     * 根据key  获取内容
     * @param key
     * @return
     */
    @GetMapping("/getValue")
    public FwResult getValue(String key) {
        String welcome = messageUtil.getMessage(key);
        return FwResult.ok(welcome);
    }

}

获取message 中的国际化配置信息,这里抽取成一个公共方法


@Component
public class MessageUtil {
    @Resource
    private MessageSource messageSource;

    public String getMessage(String code) {
        return getMessage(code, null);
    }

    /**
     *
     * @param code :对应messages配置的key.
     * @param args : 数组参数.
     * @return
     */
    public String getMessage(String code, Object[] args){
        return getMessage(code, args, "");
    }

    /**
     *
     * @param code :对应messages配置的key.
     * @param args : 数组参数.
     * @param defaultMessage : 没有设置key的时候的默认值.
     * @return
     */
    public String getMessage(String code,Object[] args,String defaultMessage){
        //这里使用比较方便的方法,不依赖request.
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }
}

1.9 启动应用测试

浏览器或Postman 输入localhost:8774/getValue?key=login.noUserId


修改语言环境localhost:8774/setLang?lang=en
浏览器或Postman 再次输入localhost:8774/getValue?key=login.noUserId

1.10 乱码处理

如果遇到国际化配置文件中存在乱码的情况可以按照下图将标记的部分勾选即可

相关推荐

「layui」表单验证:验证注册

注册界面手动验证获取短信验证码代码原文<!DOCTYPEhtml><htmllang="zh"><head>&...

Full text: Joint statement between China and Kenya on creating an inspiring example in the all-weather China-Africa community with a shared future for the new era

JointStatementBetweenthePeople'sRepublicofChinaandtheRepublicofKenyaonCreatinganInspi...

国际组织最新岗位信息送给你

国际刑警组织PostingTitleITLogisticsManagerGrade5DutyStationAbidjan,IvoryCoastDeadlineforApplicatio...

【新功能】Spire.PDF 8.12.5 支持设置表单域的可见与隐藏属性

Spire.PDF8.12.5已发布。该版本新增支持设置表单域的可见与隐藏属性、添加自定义的元数据以及给PDF文档的元数据添加新的命名空间。本次更新还增强了PDF到DOCX和图片的转换...

AI curbs show Biden&#39;s rejection of cooperation

AIcurbsshowBiden'srejectionofcooperation:ChinaDailyeditorial-Opinion-Chinadaily.com.cnT...

“煤气灯效应”上热搜,这几种有毒的“情感关系”也要注意了……

近日,“煤气灯效应”(theGaslightEffect)再次进入公众视野并登上热搜,引发网友广泛关注。那么,什么是“煤气灯效应”?以“爱”之名进行情绪控制在心理学中,通过“扭曲受害者眼中的真实”...

Qt编写推流程序/支持webrtc265/从此不用再转码/打开新世界的大门

一、前言在推流领域,尤其是监控行业,现在主流设备基本上都是265格式的视频流,想要在网页上直接显示监控流,之前的方案是,要么转成hls,要么魔改支持265格式的flv,要么265转成264,如果要追求...

写给运维的Nginx秘籍

要说Web服务器、代理服务器和调度服务器层面,目前使用最大的要数Nginx。对于一个运维工程师日常不可避免要和Nginx打交道。为了更好地使用和管理Nginx,本文就给大家介绍几个虫虫日常常用的秘籍。...

突破亚马逊壁垒,Web Unlocker API 助您轻松获取数据

在数据驱动决策的时代,电商平台的海量数据是十足金贵的。然而,像亚马逊这样的巨头为保护自身数据资产,构建了近乎完美的反爬虫防线,比如IP封锁、CAPTCHA验证、浏览器指纹识别,常规爬虫工具在这些防线面...

每日一库之 logrus 日志使用教程

golang日志库golang标准库的日志框架非常简单,仅仅提供了print,panic和fatal三个函数对于更精细的日志级别、日志文件分割以及日志分发等方面并没有提供支持.所以催生了很多第三方...

对比测评:为什么AI编程工具需要 Rules 能力?

通义灵码ProjectRules在开始体验通义灵码ProjectRules之前,我们先来简单了解一下什么是通义灵码ProjectRules?大家都知道,在使用AI代码助手的时候,有时...

python 面向对象编程

Python的面向对象编程(OOP)将数据和操作封装在对象中,以下是深度解析和现代最佳实践:一、核心概念重构1.类与实例的底层机制classRobot:__slots__=['...

Windows系统下常用的Dos命令介绍(一)

DOS是英文DiskOperatingSystem的缩写,意思是“磁盘操作系统”。DOS主要是一种面向磁盘的系统软件,说得简单些,DOS就是人给机器下达命令的集合,是存储在操作系统中的命令集。主要...

使用 Flask-Admin 快速开发博客后台管理系统:关键要点解析

一、为什么选择Flask-Admin?Flask-Admin是Flask生态中高效的后台管理框架,核心优势在于:-零代码生成CRUD界面:基于数据库模型自动生成增删改查功能-高度可定制...

Redis淘汰策略导致数据丢失?

想象一下,你的Redis服务器是一个合租宿舍,内存就是床位。当新数据(新室友)要住进来,但床位已满时,你作为宿管(淘汰策略)必须决定:让谁卷铺盖走人?Redis提供了8种"劝退"方案,...