SpringBoot错误码国际化

news2025/2/28 20:27:56

先看测试效果:   

1. 设置中文

f7d7139e9f424832bcfdc5ee3863e0cb.png

130cff648d04407f8596fc3fa198e4ee.png

2.设置英文 

374f7511d19047e999d8f22c9594cb39.png

60cb9ee209844d978fd20651436d7ee7.png

文件结构 

f8383146592c4740b0bb8fb910013b40.png

1.中文和英文的错误消息配置

bfd2cba4de2e4c4e987e3dbbc343d3aa.png

package com.ldj.mybatisflex.common;

import lombok.Getter;

/**
 * User: ldj
 * Date: 2025/1/12
 * Time: 17:50
 * Description: 异常消息枚举
 */
@Getter
public enum ExceptionEnum {
    
    //# code命名规则:模块编码 + 唯一序号 11表示用户管理模块

    LOGIN_EXCEPTION(1101),
    OTHER_EXCEPTION(1102);

    private Integer code;

    ExceptionEnum(Integer code) {
        this.code = code;
    }
}

2.统一响应类 

package com.ldj.mybatisflex.common;

import lombok.Getter;
import lombok.Setter;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.ResourceBundle;

/**
 * User: ldj
 * Date: 2025/1/12
 * Time: 18:08
 * Description: 统一响应类
 */
@Getter
@Setter
public class Response<T> {

    private static final String basePath = "i18n/message";

    private static final Integer successCode = 200;
    private static final String success = "成功!";

    private static final Integer failCode = 500;
    private static final String fail = "失败!";

    private Integer code;

    private String message;

    private T data;

    public static <T>Response<T> success(T data) {
        Response<T> response = new Response<>();
        response.setCode(200);
        response.setMessage(success);
        response.setData(data);
        return response;
    }

    public static <T>Response<T> fail() {
        return fail(failCode, fail);
    }


    //关键代码是读取国际化的配置文件,作为错误提示消息
    public static <T>Response<T> fail(ExceptionEnum exceptionEnum, T date) {
        Response<T> response = new Response<>();
        response.setCode(exceptionEnum.getCode());
        ResourceBundle bundle = ResourceBundle.getBundle(basePath, LocaleContextHolder.getLocale());
        String message = bundle.getString(exceptionEnum.getCode().toString());
        response.setMessage(message);
        response.setData(date);
        return response;
    }

    public static <T>Response<T> fail(Integer code, String message) {
        Response<T> response = new Response<>();
        response.setCode(code);
        response.setMessage(message);
        response.setData(null);
        return response;
    }
}

 3.登录拦截器

package com.ldj.mybatisflex.interceptor;

import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * User: ldj
 * Date: 2025/1/12
 * Time: 21:05
 * Description: 登录拦截器
 */
@Order(1)
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //需要前端传过来的,这里一直是null
        String language = request.getHeader("language");
        //假设前端传"en_US"
        //language = "en_US";

        //默认是zh_CN
        if (language == null || "".equals(language) || "zh_CN".equalsIgnoreCase(language)) {
            LocaleContext localeContext = new SimpleLocaleContext(Locale.SIMPLIFIED_CHINESE);
            LocaleContextHolder.setLocaleContext(localeContext);
        }else {
            LocaleContext localeContext = new SimpleLocaleContext(Locale.US);
            LocaleContextHolder.setLocaleContext(localeContext);
        }

        System.out.println("配置语言:" + LocaleContextHolder.getLocale());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //请求结束后记得清理 ThreadLocal里面的值,好让垃圾回收器回收
        LocaleContextHolder.resetLocaleContext();
    }
}

 4.配置webmvc 应用登录拦截器

package com.ldj.mybatisflex.config;

import com.ldj.mybatisflex.interceptor.LoginUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * User: ldj
 * Date: 2025/1/12
 * Time: 21:00
 * Description: No Description
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginUserInterceptor loginUserInterceptor;

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

5.测试

package com.ldj.mybatisflex.controller;

import com.ldj.mybatisflex.common.ExceptionEnum;
import com.ldj.mybatisflex.common.Response;
import com.ldj.mybatisflex.model.dao.UerInfoDAO;
import com.ldj.mybatisflex.model.dto.UserLoginReqDTO;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * User: ldj
 * Date: 2024/11/17
 * Time: 16:55
 * Description: No Description
 */
@RestController
@RequestMapping("/userInfo")
@CrossOrigin(maxAge = 3600)
public class UserInfoController {
    
    @PostMapping(value = "/login")
    public Response<UerInfoDAO> login(@RequestBody @Valid UserLoginReqDTO userLoginReqDTO){
        return Response.fail(ExceptionEnum.LOGIN_EXCEPTION, null);
    }
}

总结,这有个问题,每次读取配置文件都要操作io流,性能比直接定义在枚举差,3个字段,一个code ,1个cnMsg  ,1个enMsg,再写个方法判断是否中,英获取消息。

但是如果是法语,就失去灵活性,要改代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2278924.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

软考高级5个资格、中级常考4个资格简介及难易程度排序

一、软考高级5个资格 01、网络规划设计师 资格简介&#xff1a;网络规划设计师要求考生具备全面的网络规划、设计、部署和管理能力&#xff1b;该资格考试适合那些在网络规划和设计方面具有较好理论基础和较丰富从业经验的人员参加。 02、系统分析师 资格简介&#xff1a;系统分…

如何通过 Apache Airflow 将数据导入 Elasticsearch

作者&#xff1a;来自 Elastic Andre Luiz 了解如何通过 Apache Airflow 将数据导入 Elasticsearch。 Apache Airflow Apache Airflow 是一个旨在创建、安排&#xff08;schedule&#xff09;和监控工作流的平台。它用于编排 ETL&#xff08;Extract-Transform-Load&#xff0…

STM32 学习笔记【补充】(十)硬件I2C读写MPU6050

该系列为笔者在学习STM32过程&#xff08;主线是江科大的视频&#xff09;中的记录与发散思考。 初学难免有所纰漏、错误&#xff0c;还望大家不吝指正&#xff0c;感谢~ 一、I2C 外设简介 I2C&#xff08;Inter-Integrated Circuit&#xff09;是一种多主多从的串行通信协议…

QT信号槽 笔记

信号与槽就是QT中处理计算机外设响应的一种机制 比如敲击键盘、点击鼠标 // 举例&#xff1a; 代码&#xff1a; connect(ls,SIGNAL(sig_chifanla()),ww,SLOT(slot_quchifan())); connect(ls,SIGNAL(sig_chifanla()),zl,SLOT(slot_quchifan()));connect函数&#xff1a;这是…

【React】插槽渲染机制

目录 通过 children 属性结合条件渲染通过 children 和 slot 属性实现具名插槽通过 props 实现具名插槽 在 React 中&#xff0c;并没有直接类似于 Vue 中的“插槽”机制&#xff08;slot&#xff09;。但是&#xff0c;React 可以通过 props和 children 来实现类似插槽的功能…

openharmony电源管理子系统

电源管理子系统 简介目录使用说明相关仓 简介 电源管理子系统提供如下功能&#xff1a; 重启服务&#xff1a;系统重启和下电。系统电源管理服务&#xff1a;系统电源状态管理和休眠运行锁管理。显示相关的能耗调节&#xff1a;包括根据环境光调节背光亮度&#xff0c;和根…

数据库(中)11讲

用颜色、有否下划线对应&#xff01; E-R图

图像去雾数据集的下载和预处理操作

前言 目前&#xff0c;因为要做对比实验&#xff0c;收集了一下去雾数据集&#xff0c;并且建立了一个数据集的预处理工程。 这是以前我写的一个小仓库&#xff0c;我决定还是把它用起来&#xff0c;下面将展示下载的路径和数据处理的方法。 下面的代码均可以在此找到。Auo…

STM32入门教程-示例程序(按键控制LED光敏传感器控制蜂鸣器)

1. LED Blink&#xff08;闪烁&#xff09; 代码主体包含&#xff1a;LED.c key.c main.c delay.c&#xff08;延时防按键抖动&#xff09; 程序代码如下&#xff08;涉及RCC与GPIO两个外设&#xff09;&#xff1a; 1.使用RCC使能GPIO时钟 RCC_APB2PeriphClockC…

一本书揭秘程序员如何培养架构思维!

在程序员的职业规划中&#xff0c;成为软件架构师是一个非常有吸引力的选择。但是对于如何才能成为一名架构师&#xff0c;不少同学认为只要代码写得好&#xff0c;就能得到公司提拔&#xff0c;晋升为架构师。 还真不是这样的&#xff0c;如果不具备架构思维&#xff0c;即使…

Flink(十):DataStream API (七) 状态

1. 状态的定义 在 Apache Flink 中&#xff0c;状态&#xff08;State&#xff09; 是指在数据流处理过程中需要持久化和追踪的中间数据&#xff0c;它允许 Flink 在处理事件时保持上下文信息&#xff0c;从而支持复杂的流式计算任务&#xff0c;如聚合、窗口计算、联接等。状…

Vue2+OpenLayers实现点位拖拽功能(提供Gitee源码)

目录 一、案例截图 二、安装OpenLayers库 三、代码实现 3.1、初始化变量 3.2、创建一个点 3.3、将点添加到地图上 3.4、实现点位拖拽 3.5、完整代码 四、Gitee源码 一、案例截图 可以随意拖拽点位到你想要的位置 二、安装OpenLayers库 npm install ol 三、代码实现…

2024年博客之星年度评选—创作影响力评审入围名单公布

2024年博客之星活动地址https://www.csdn.net/blogstar2024 TOP 300 榜单排名 用户昵称博客主页 身份 认证 评分 原创 博文 评分 平均 质量分评分 互动数据评分 总分排名三掌柜666三掌柜666-CSDN博客1001002001005001wkd_007wkd_007-CSDN博客1001002001005002栗筝ihttps:/…

NVIDIA发布个人超算利器project digital,标志着ai元年的开启

上图NVIDIA公司创始人兼首席执行官 黄仁勋&#xff08;Jensen Huang&#xff09; 这些年被大家熟知的赛博朋克风格一直都是未来的代言词&#xff0c;可以承载人类记忆的芯片&#xff0c;甚至能独立思考的仿生人&#xff0c;现在&#xff0c;随着NVIDIA的project digital发布之后…

(一)afsim第三方库编译

注意&#xff1a;防止奇怪的问题&#xff0c;源码编译的路径最好不要有中文&#xff0c;请先检查各文件夹名 AFSIM版本 Version&#xff1a; 2.9 Plugin API Version&#xff1a; 11 软件环境 操作系统&#xff1a; Kylin V10 SP1 项目构建工具: cmake-3.26.0-linux-aarch6…

2025.1.17——三、SQLi regexp正则表达式|

题目来源&#xff1a;buuctf [NCTF2019]SQLi1 目录 一、打开靶机&#xff0c;整理信息 二、解题思路 step 1&#xff1a;正常注入 step 2&#xff1a;弄清关键字黑名单 1.目录扫描 2.bp爆破 step 3&#xff1a;根据过滤名单构造payload step 4&#xff1a;regexp正则注…

docker的数据卷与dockerfile自定义镜像

docker的数据卷与dockerfile自定义镜像 一. docker的数据卷数据卷容器 二. dockerfile自定义镜像2.1 dockerfile的命令格式镜像的操作命令add和copy的区别 容器启动的命令 2.2 run命令2.3 其它端口映射 三. 练习 一. docker的数据卷 容器于宿主机之间&#xff0c;或者容器和容…

【python_钉钉群发图片】

需求&#xff1a; **在钉钉群发图片&#xff0c;需要以图片的形式展示&#xff0c;如图所示&#xff1a;**但是目前影刀里面没有符合条件的指令 解决方法&#xff1a; 1、在钉钉开发者后台新建一个自建应用&#xff0c;发版&#xff0c;然后获取里面的appkey和appsecret&am…

新星杯-ESP32智能硬件开发--ESP32的I/O组成-系统中断矩阵

本博文内容导读&#x1f4d5;&#x1f389;&#x1f525; ESP32开发板的中断矩阵、功能描述与实现、相关API和示例程序进行介绍 ESP32中断矩阵将任一外部中断源单独分配到每个CPU的任一外部中断上&#xff0c;提供了强大的灵活性&#xff0c;能适应不同的应用需求。 ESP32中断主…

软路由系统iStoreOS 一键安装 docker compose

一键安装命令 大家好&#xff01;今天我来分享一个快速安装 docker-compose 的方法。以下是我常用的命令&#xff0c;当前版本是 V2.32.4。如果你需要最新版本&#xff0c;可以查看获取docker compose最新版本号 部分&#xff0c;获取最新版本号后替换命令中的版本号即可。 w…