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

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

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

国际化是每个大型公司官网或者技术文档都会有的,比如前端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 乱码处理

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

相关推荐

EU Said to Accept a 10% U.S. Universal Tariff while Seeking Exemptions for Key Sectors

TMTPOST--TheEuropeanUnionmaymakeconcessionstosecureexemptionsfromtariffsonkeysectors...

抖音品质建设 - iOS启动优化《实战篇》

前言启动是App给用户的第一印象,启动越慢,用户流失的概率就越高,良好的启动速度是用户体验不可缺少的一环。启动优化涉及到的知识点非常多,面也很广,一篇文章难以包含全部,所以拆分成两部分:原理和实战...

荷兰引进美国诗人阿曼达·戈尔曼诗作,因译者肤色遭抵制

记者|刘亚光阿曼达在拜登就职典礼上朗诵诗歌。图源:PatrickSemansky/AssociatedPress阿曼达·戈尔曼(AmandaGorman)出生于1998年,自小患有语言障碍,...

EU and U.S. Upbeat on Trade Deal Ahead of July Deadline

TMTPOST--TheEuropeanUnionandtheUnitedStatesseemupbeatontheirtradeagreementtoavoidtr...

“过期食品”英文怎么说?(过期食品)

在购买食品时,我们都会特别留意一下食物的保质期有多久,是否新鲜,以免买到过期的商品。TheafternoonteaspreadatThePeninsulaBoutiqueandCaf...

世界首富撩妹露骨短信遭曝光 网友评论亮了

原标题:世界首富如何撩妹?亚马逊创始人贝索斯给情妇的露骨短信曝光这周最大的一个瓜,可能就是亚马逊首席执行官杰夫·贝佐斯(JeffBezos)与妻子麦肯齐(MacKenzie)离婚的惊人消息。紧接...

征收熊孩子“尖叫费”不合理?店主回怼网友

爱尔兰一家很受欢迎的咖啡馆要收“孩童尖叫费”,网友们。。。爱尔兰一咖啡店店主5月4日在脸书发帖,表示要向带有吵闹孩童的顾客多收15%的额外费用,引发了大批网友的议论。原贴内容如下:图viaFaceb...

Rationality, objectivity and pragmatism win the day in Geneva to benefit of all

ApressbriefingisheldbytheChinesesidefollowingtheChina-UShigh-levelmeetingoneconomica...

Dify「模板转换」节点终极指南:动态文本生成进阶技巧(附代码)Jinja2引擎解析|6大应用场景实战

这篇文章是关于Dify「模板转换」节点的终极指南,解析了基于Jinja2模板引擎的动态文本生成技巧,涵盖多源文本整合、知识检索结构化、动态API构建及个性化内容生成等六大应用场景,助力开发者高效利用模...

微软 Edge 浏览器 96.0.4664.93 稳定版发布:修复大量安全问题

IT之家12月12日消息,据外媒mspoweruser消息,微软12月11日为Edge浏览器推出了96.0.4664.93稳定版。该版本没有增加新功能,而是修复了大量漏洞,...

HarmonyOS NEXT仓颉开发语言实战案例:健身App

各位好,今日分享一个健身app的首页:这个页面看起比之前的案例要稍微复杂一些,主要在于顶部部分,有重叠的背景,还有偏移的部分。重叠布局可以使用Stack容器实现,超出容器范围的偏移可以使用负数间距来实...

如果使用vue3.0实现一个modal,你会怎么设计?

这是个很好的问题!设计一个Vue3.0Modal时,我建议按照可复用、高扩展、简洁的原则来实现。下面我给你一个清晰的设计思路,涵盖组件拆分、使用方式以及Vue3中特性(如Telepor...

在进行APP切图的前,我们需要做什么?

切图是个技术活,小伙伴们千万不能忽视切图的重要性噢,前文介绍了设计的七大元素,那么我们现在来看看在切图之前,我们需要做什么呢?。1、和客户端的技术沟通好用不同的框架来实现的时候,图会有不一样的切法。...

独立开发问题记录-margin塌陷(独立提出历史问题)

一、概述往事如风,一周就过去了。上周在Figma里指点江山,这周在前端代码里卑微搬砖。回想上周,在Figma中排列组合,并且精确到1像素。每设计出一个页面,成就感就蹭蹭往上涨。没想到还没沾沾自喜多久,...

循序渐进Vue+Element 前端应用开发(8)—树列表组件的使用

在我前面随笔《循序渐进VUE+Element前端应用开发(6)---常规Element界面组件的使用》里面曾经介绍过一些常规的界面组件的处理,主要介绍到单文本输入框、多文本框、下拉列表,以及按钮...