定义一个处理核心类

I18nController.java

package com.ewe.core.i18n;import java.util.Locale;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;@Controller
public class I18nController {private static final Logger LOGGER = LoggerFactory.getLogger(I18nController.class);private MessageSource messageSource;@Value("${spring.messages.basename}") private String basename;@Value("${spring.messages.cache-seconds}") private long cacheMillis;@Value("${spring.messages.encoding}") private String encoding;/*** 初始化* @return*/private MessageSource initMessageSource() { ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();LOGGER.info("baseName====>:" + this.basename); messageSource.setBasename(basename); messageSource.setDefaultEncoding(encoding); messageSource.setCacheMillis(cacheMillis);return messageSource; }/*** 设置当前的返回信息* @param request* @param code* @return*/public String getMessage(HttpServletRequest request,String code){if(messageSource==null){messageSource=initMessageSource();}String lauage=request.getHeader("Accept-Language");//默认没有就是请求地区的语言Locale locale=null;if(lauage==null){locale=request.getLocale();}else if("en-US".equals(lauage)){locale=Locale.ENGLISH;}   else if("zh-CN".equals(lauage)){locale=Locale.CHINA;}//其余的不正确的默认就是本地的语言else{locale=request.getLocale();}String result=null;try {result = messageSource.getMessage(code, null, locale);} catch (NoSuchMessageException e) {LOGGER.error("Cannot find the error message of internationalization, return the original error message.");}if(result==null){return code;}return result;}
}

application配置文件加入如下配置

#message-source
spring.messages.basename=i18n/messages
#-1 no expried
spring.messages.cache-seconds= -1
spring.messages.encoding=UTF-8

创建以上的message信息文件

messages_en.properties

NotFound=Not found information.
NotFoundUser=This user doesn't exist.
OperationError=Error operation !
SuccessOperation=Success operation !
Exist=This data already exists.
ExistUser=This user name already exists !
NewPasswordError=The new password is inconsistent with the confirmation password!
SamePassword=Same old and new passwords!
LogoutSuccess=Logout success!
ErrorPassword=Original password error!
LoginError=User name or password incorrect.
UserNameNull= The user name can not be null.
EmailNull=The email can not be null.
PasswordNull=The password can not be null.
PhoneStandbyNull=The phoneStandby can not be null.
MatchPassword=The two passwords don't match.
NewPasswordNull=The new password can not be null.
OldPasswordNull=The old password can not be null.
EmailIncorrect=The email is incorrect.
PhoneIncorrect=The phone is incorrect.
PhoneStandbyIncorrect=The standby phone is incorrect.
PhoneEmergencyIncorrect=The emergency phone is incorrect.
ExpiredToken=Expired or invalid JWT token.
AccessDenied=Access Denied.
TimeZoneError=Time zone error or nonexistence.
UserIdError=The user id is incorrect or empty.
NumberFormatException=Data conversion error.
DateFormatError=The date is not in the correct format.
DataNull=The data can not be null.

messages_zh_CN.properties

NotFound=\u6CA1\u6709\u67E5\u8BE2\u5230\u4FE1\u606F\u3002
NotFoundUser=\u5F53\u524D\u8FD9\u4E2A\u7528\u6237\u4E0D\u5B58\u5728\u3002
OperationError=\u64CD\u4F5C\u9519\u8BEF\uFF01
SuccessOperation=\u64CD\u4F5C\u6210\u529F\uFF01
Exist=\u5F53\u524D\u8FD9\u4E2A\u6570\u636E\u5DF2\u5B58\u5728\uFF01
ExistUser=\u7528\u6237\u540D\u5DF2\u5B58\u5728\uFF01
NewPasswordError=\u65B0\u5BC6\u7801\u548C\u65E7\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF01
SamePassword=\u65B0\u65E7\u5BC6\u7801\u4E00\u81F4\uFF01
LogoutSuccess=\u767B\u51FA\u6210\u529F\uFF01
ErrorPassword=\u539F\u5BC6\u7801\u9519\u8BEF\uFF01
LoginError=\u7528\u6237\u540D\u6216\u8005\u5BC6\u7801\u4E0D\u6B63\u786E\uFF01
UserNameNull= \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A\uFF01
EmailNull=\u90AE\u7BB1\u4E0D\u80FD\u4E3A\u7A7A\uFF01
PasswordNull=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A
PhoneStandbyNull=\u5907\u7528\u8054\u7CFB\u7535\u8BDD\u4E0D\u80FD\u4E3A\u7A7A\uFF01
MatchPassword=\u4FE9\u6B21\u8F93\u5165\u7684\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF01
NewPasswordNull=\u65B0\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01
OldPasswordNull=\u65E7\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01
EmailIncorrect=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneIncorrect=\u624B\u673A\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneStandbyIncorrect=\u5907\u7528\u7535\u8BDD\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneEmergencyIncorrect=\u7D27\u6025\u7535\u8BDD\u683C\u5F0F\u4E0D\u6B63\u786E
ExpiredToken=\u4EE4\u724C\u5DF2\u7ECF\u8FC7\u671F\uFF01
AccessDenied=\u62D2\u7EDD\u8BBF\u95EE\uFF01
TimeZoneError=\u65F6\u533A\u586B\u5199\u9519\u8BEF\u6216\u8005\u4E0D\u5B58\u5728\uFF01
UserIdError=\u7528\u6237\u7684\u7F16\u53F7\u4E0D\u6B63\u786E\u6216\u8005\u4E3A\u7A7A\uFF01
NumberFormatException=\u6570\u636E\u8F6C\u6362\u9519\u8BEF\uFF01
DateFormatError=\u65E5\u671F\u7684\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
ConfigError=\u6743\u9650\u914D\u7F6E\u6587\u4EF6\u914D\u7F6E\u51FA\u9519\uFF01
DataNull=\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A\uFF01

以上就配置好了 怎么调用呢?

 @Autowiredprivate I18nController i18n;然后再方法里面调用这个
//根据键值对获取信息try {messageFound=i18n.getMessage(request, messageFound);} catch (Exception e) {// TODO Auto-generated catch blockmessageFound=e.getMessage();e.printStackTrace();}

可以参考我的异常信息处理

只能参考异常处理

package com.ewe.core.exception;/*** 在过滤器中抛出的异常信息,比如404 400 401 403 */
import java.io.IOException;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;import com.ewe.core.dto.ErrorDto;
import com.ewe.core.i18n.I18nController;
/*** 返回Rest错误信息** @author will* @author qianyi* @since 1.0*/@RestController
public class GlobalExceptionHandler implements ErrorController {private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);private static final String PATH = "/error";@Autowiredprivate I18nController i18n;@Autowiredprivate ErrorAttributes errorAttributes;@RequestMapping(value = { "${error.path:/error}" }, produces = { "text/html" })public ErrorDto errorHtml(HttpServletRequest request,HttpServletResponse response) throws IOException {return error(request, response);}@RequestMapping({ "${error.path:/error}" })@ResponseBodypublic ErrorDto error(HttpServletRequest request,HttpServletResponse response) throws IOException {ErrorDto info = new ErrorDto();Map<String,Object> errorAttributes = getErrorAttributes(request, true);// System.out.println(errorAttributes);Integer status=(Integer)errorAttributes.get("status");String path=(String)errorAttributes.get("path");String trace=(String)errorAttributes.get("trace");String exception=(String)errorAttributes.get("exception");String messageFound=(String)errorAttributes.get("message");if(messageFound.equalsIgnoreCase("No message available")){messageFound="AccessDenied";}else if(messageFound.indexOf("Access Denied")!=-1){status=401;messageFound="AccessDenied";}else if(messageFound.indexOf("Unauthorized")!=-1){status=401;}else if(messageFound.indexOf("Expired or invalid JWT token")!=-1){status=401;messageFound="ExpiredToken";}else if(messageFound.indexOf("NumberFormatException")!=-1){messageFound="NumberFormatException";}else if(messageFound.indexOf("Can not")!=-1&&messageFound.indexOf("java.util.Date")!=-1){messageFound="DateFormatError";}//根据键值对获取信息try {messageFound=i18n.getMessage(request, messageFound);} catch (Exception e) {// TODO Auto-generated catch blockmessageFound=e.getMessage();e.printStackTrace();}String allMessage="\nMessage:"+messageFound+".\n When request path:"+path+". Here produces an exception:" + exception + ".\nTrace:\n"+trace;// 打印异常信息:info.setCode(status);info.setMessage(lcaolGeMessage(messageFound));LOGGER.error(allMessage);return info;}/*** 处理异常*/public String lcaolGeMessage(String messageString){if(messageString.indexOf(":")!=messageString.lastIndexOf(":")){messageString=messageString.substring(0,messageString.indexOf(":"))+". "+messageString.substring(messageString.indexOf(":")+1).substring(0,messageString.substring(messageString.indexOf(":")+1).indexOf(":"));}return messageString;}@Overridepublic String getErrorPath() {return PATH;}/*** 根据请求处理数据* @param request* @param includeStackTrace* @return*/private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {RequestAttributes requestAttributes = new ServletRequestAttributes(request);//System.out.println(requestAttributes.get);return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);}
}

SpringBoot的国际化错误信息返回相关推荐

  1. springboot 控制台输出错误信息_SpringBoot 三招组合拳,手把手教你打出优雅的后端接口...

    Python实战社群 Java实战社群 长按识别下方二维码,按需求添加 扫码关注添加客服 进Python社群▲ 扫码关注添加客服 进Java社群▲ 作者丨RudeCrab 一.前言 一个后端接口大致分 ...

  2. springboot 控制台输出错误信息_springboot(6)——整合日志

    概述 我们在平时开发项目的时候想知道程序运行情况一般可以使用sysout.print();打印一些关键的代码或者通过debug查看运行状态,但是对于这种sysout.print();很现任出现代码多余 ...

  3. springboot 控制台输出错误信息_Spring boot使用logback实现日志配置

    前言 日志是我们系统必备的功能之一,可以帮助我们开发人员定位系统的异常.错误以及运行流程的重要的工具.今天老顾就来介绍一下Spring boot的默认的logback日志框架. 常用日志组件 java ...

  4. springboot 控制台输出错误信息_springboot日志详解

    一. 主流日志框架 市场上存在非常多的日志框架. JUL(java.util.logging),JCL(Apache Commons Logging),Log4j,Log4j2,Logback. SL ...

  5. springboot 控制台输出错误信息_高级码农Spring Boot实战进阶之过滤器、拦截器的使用...

    众所周知的Spring Boot是很优秀的框架,它的出现简化了新Spring应用的初始搭建以及开发过程,大大减少了代码量,目前已被大多数企业认可和使用.这个专栏将对Spring Boot框架从浅入深, ...

  6. java异常自定义返回信息,Spring Boot 如何自定义返回错误码错误信息

    说明 在实际的开发过程中,很多时候要定义符合自己业务的错误码和错误信息,而不是统一的而不是统一的下面这种格式返回到调用端 INTERNAL_SERVER_ERROR(500, "Intern ...

  7. EasyExcel如何返回业务处理中的错误信息

    前言 又又又接手老项目 进行改造- 之前poi写的excel导入会导致oom内存溢出,调了内存也没用 就用EasyExcel重写了下 基于原项目结构的写 确实好难受 一句话概括本文: 引用传递 开始 ...

  8. 如何设计系统的错误码及错误信息

    作者:朱金灿 来源:http://blog.csdn.net/clever101 一个软件系统,肯定是涉及到很多错误信息.比如用户执行出错了,软件需要将错误信息返回给用户.那么如何设计错误码及错误信息 ...

  9. SpringBoot 数据验证错误处理

    在之前的程序里面如果一旦出现了错误之后就会出现一堆大白板,这个白板会有一些错误信息(虽然这些错误信息你可能看不懂,但是这些错误信息依然要告诉给用户).在SpringBoot里面针对于错误的处理一共提供 ...

最新文章

  1. Django web框架-----Django连接现有mysql数据库
  2. 你还在用Swagger?试试这个神器!
  3. weifenluo与notifyIcon小细节
  4. Hbase(1)——基础语句(1)
  5. jmeter 入门操作
  6. python工资一般多少西安-在西安为什么对Python编程需求这么大?工资这么高?
  7. 13. PHP 数组
  8. 关于form提交后展示遮罩及显示进度条gif问题
  9. Faster R-CNN算法
  10. ZendStudio
  11. 人人商城V3配置添加对接威信小程序直播,前后端教程。
  12. 白话布隆过滤器(BloomFilter)
  13. [19保研]中国科学院沈阳计算技术研究所教育中心2019年保研夏令营通知
  14. 第四届“安洵杯”网络安全挑战赛MISC-Writeup
  15. 恶意程序检测之malconv模型
  16. 华为荣耀3c手机语言设置在哪个文件夹,(科普)详解Android系统SD卡各类文件夹名称...
  17. 群晖硬盘已损毁 Linux 修复,群晖NAS提示空间损毁修复纪实 | Yeboyzq Blog
  18. 计算机安全模式win7,win7安全模式下怎么恢复系统
  19. 字节日常实习生面试 无了~
  20. 爬虫必备,案例对比 Requests、Selenium、Scrapy 爬虫库!

热门文章

  1. springboot报错(三) webjars被拦截或找不到
  2. 中级软件设计师备考攻略
  3. 冯诺依曼结构计算机方案包含3个要点,冯诺依曼体系结构计算机的要点和工作过程.doc...
  4. Yolov5 网络改进之增加SE、CBAM、CA、ECA等注意力机制
  5. 射影几何----渐近线方程公式
  6. 两个ip是否在同一网段?
  7. 基于CDMA网络的自来水厂水井生产监控系统通信解决方案
  8. Windows 11关闭系统更新的方法有哪些?
  9. mysql导入数据时 USING BTREE 错误解决办法
  10. js判断手机上是否安装某APP