若依 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;
    }
}
相关推荐
J_liaty8 小时前
SpringBoot + EMQX:打造物联网设备数据双向通讯的完整解决方案
spring boot·物联网·emqx
Coder_Boy_9 小时前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解
java·数据库·人工智能·spring boot
crossaspeed10 小时前
Java-SpringBoot的启动流程(八股)
java·spring boot·spring
这儿有个昵称11 小时前
互联网大厂Java面试场景:从Spring框架到微服务架构的提问解析
java·spring boot·微服务·kafka·grafana·prometheus·数据库优化
Coder_Boy_12 小时前
基于SpringAI的在线考试系统-DDD(领域驱动设计)核心概念及落地架构全总结(含事件驱动协同逻辑)
java·人工智能·spring boot·微服务·架构·事件驱动·领域驱动
小北方城市网13 小时前
SpringBoot 集成 RabbitMQ 实战(消息队列解耦与削峰):实现高可靠异步通信
java·spring boot·python·微服务·rabbitmq·java-rabbitmq·数据库架构
程序员老徐13 小时前
SpringBoot嵌入Tomcat注册Servlet、Filter流程
spring boot·servlet·tomcat
guslegend13 小时前
第1章:快速入门SpringBoot
spring boot
Coder_Boy_14 小时前
基于SpringAI的在线考试系统-考试模块前端页面交互设计及优化
java·数据库·人工智能·spring boot
李慕婉学姐15 小时前
Springboot旅游景点管理系统2fj40iq6(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端