若依 springBoot 配置国际化

代码如下,配置文件在资源中。Language 取值en-US zh-CN 和前端商量好就行

java 复制代码
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

package com.ruoyi.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yxy
 * @Date: 2025/11/11/16:42
 * @Description:
 */

public class MyI18nInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        final String key = "Language";
        String language = request.getHeader(key);

        if (language != null && language.matches("[a-zA-Z]{2}[-][a-zA-Z]{2}"))
        {
            //如果请求头中包含符合格式的语言信息,例如"en-US"
//            log.info("当前语言={}",language);

            //根据语言信息创建Locale对象,例如,"en-US"分割为语言"en"和国家/地区"US"
            Locale locale = new Locale(language.split("-")[0], language.split("-")[1]);
//            log.info("loc" + locale);
            LocaleContextHolder.setLocale(locale);
        }
        else {
            //如果请求头中没有有效的语言信息,则设置默认语言
            Locale defaultLocale = Locale.US;
//            log.info("未指定语言,使用默认语言={}", defaultLocale);
            LocaleContextHolder.setLocale(defaultLocale);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
    {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex)
    {

    }
}



package com.ruoyi.framework.config;

import com.ruoyi.common.config.MyI18nInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import com.ruoyi.common.constant.Constants;

/**
 * 资源文件配置加载
 * 
 * @author ruoyi
 */
@Configuration
public class I18nConfig implements WebMvcConfigurer
{
//    @Bean
//    public LocaleResolver localeResolver()
//    {
//        SessionLocaleResolver slr = new SessionLocaleResolver();
//        // 默认语言
//        slr.setDefaultLocale(Constants.DEFAULT_LOCALE);
//        return slr;
//    }
//
//    @Bean
//    public LocaleChangeInterceptor localeChangeInterceptor()
//    {
//        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
//        // 参数名
//        lci.setParamName("lang");
//        return lci;
//    }
//
//    @Override
//    public void addInterceptors(InterceptorRegistry registry)
//    {
//        registry.addInterceptor(localeChangeInterceptor());
//    }


    @Bean
    public ResourceBundleMessageSource messageSource(){

        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        //这里设置自己的文件名
        source.setBasenames("i18n.message","i18n.exception","i18n.business", "i18n.export");
        source.setUseCodeAsDefaultMessage(true);
        source.setDefaultEncoding("UTF-8");
        return source;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        //注册拦截器
        MyI18nInterceptor myI18nInterceptor = new MyI18nInterceptor();
        InterceptorRegistration loginRegistry = registry.addInterceptor(myI18nInterceptor);

        //拦截路径
        loginRegistry.addPathPatterns("/**");
    }
}


package com.ruoyi.common.utils;

import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

//@Component
public class MessageUtils {
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args)
    {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }


}



package com.ruoyi.web.controller;


import com.ruoyi.common.utils.MessageUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController66 {

    @GetMapping("/test22")
    public String test() {
        // 调用国际化消息
        String successMsg = MessageUtils.message("sys.common.success");
        String loginTitle = MessageUtils.message("user.login.title");
        String welcomeMsg = MessageUtils.message("user.login.welcome", "张三"); // 带参数
        return successMsg + " | " + loginTitle + " | " + welcomeMsg;
    }
}
相关推荐
JosieBook2 小时前
【SpringBoot】32 核心功能 - 单元测试 - JUnit5 单元测试中的嵌套测试与参数化测试详解
spring boot·单元测试·log4j
小坏讲微服务3 小时前
Nginx集群与SpringCloud Gateway集成Nacos的配置指南
spring boot·nginx·spring cloud·gateway
计算机学姐3 小时前
基于SpringBoot的新闻管理系统【协同过滤推荐算法+可视化统计】
java·vue.js·spring boot·后端·spring·mybatis·推荐算法
一 乐4 小时前
远程在线诊疗|在线诊疗|基于java和小程序的在线诊疗系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小程序
serendipity_hky4 小时前
【微服务 - easy视频 | day04】Seata解决分布式事务
java·spring boot·分布式·spring cloud·微服务·架构
大菠萝学姐4 小时前
基于springboot的旅游攻略网站设计与实现
前端·javascript·vue.js·spring boot·后端·spring·旅游
q_19132846955 小时前
基于SpringBoot+Vue2的美食菜谱美食分享平台
java·spring boot·后端·计算机·毕业设计·美食
刘一说6 小时前
Spring Boot 中的定时任务:从基础调度到高可用实践
spring boot·后端·wpf
小坏讲微服务6 小时前
使用 Spring Cloud Gateway 实现集群
java·spring boot·分布式·后端·spring cloud·中间件·gateway