若依 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;
    }
}
相关推荐
学长毕设8 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
学长毕设9 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
杨凯凡10 小时前
Spring Boot SSE 上线后不实时、频繁断线?Nginx 缓冲、心跳与连接回收实战
spring boot·后端·nginx
学长毕设12 小时前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏
码云社区17 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件17 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
杨运交18 小时前
091-功能模块-API Key 管理功能模块解析:feature-sa-token 架构设计与数据库持久化
spring boot
行百里er18 小时前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud
有个傻瓜18 小时前
一次「查到别家门店订单」的线上事故:Spring Boot 3 + MyBatis-Plus 多租户隔离踩坑复盘
spring boot·mybatis-plus·多租户·ruoyi-vue-plus·线上故障复盘
学长毕设1 天前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端