springboot统一返回json数据格式并配置系统异常拦截
本文链接:https://blog.csdn.net/syystx/article/details/82870217
通常进行前后端分离开发时我们需要定义统一的json数据交互格式并对系统未处理异常进行处理。以下具体介绍在springboot中的实现过程,通过该章节代码可实现框架统一异常处理,并当后台接口反馈类型不为统一格式时能够进行重新包装成统一格式进行返回。
具体实现如下:
1、定义统一返回格式
public class RtnMsg{
private String rtnCode;
private String rtnMsg="";
private Object msg;
public RtnMsg(String rtnCode,String rtnMsg,Object msg){
this.rtnCode = rtnCode;
this.rtnMsg = rtnMsg;
this.msg = msg;
}
public RtnMsg(String rtnCode,String rtnMsg){
this.rtnCode = rtnCode;
this.rtnMsg = rtnMsg;
}
public RtnMsg(){
}
public String getRtnCode() {
return rtnCode;
}
public void setRtnCode(String rtnCode) {
this.rtnCode = rtnCode;
}
public String getRtnMsg() {
return rtnMsg;
}
public void setRtnMsg(String rtnMsg) {
this.rtnMsg = rtnMsg;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
}
2、设置常用错误码
public class RtnCode {
//正常返回
public static final String STATUS_OK = "000";
//参数错误
public static final String STATUS_PARAM = "001";
//接口未发现
public static final String STATUS_NOFOUND = "404";
//捕获到异常
public static final String STATUS_SYSERROR = "500";
}
3、定义未处理异常统一拦截
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author suntongxin
* Create on 2017年12月12日下午1:55:12
* All right reserved
*/
@ControllerAdvice
public class CommExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public RtnMsg handle(Exception e){
RtnMsg msg = new RtnMsg(RtnCode.STATUS_SYSERROR, "系统异常,异常原因:"+e.getMessage());
return msg;
}
4、注入拦截response的bean对象
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author suntongxin
* Create on 2017年12月12日下午1:55:27
* All right reserved
*/
@Configuration
public class RtnMsgConfig{
@Bean
public ResponseBodyWrapFactoryBean getResponseBodyWrap(){
return new ResponseBodyWrapFactoryBean();
}
}
5、设置bean过滤原则
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
/**
* @author suntongxin
* Create on 2017年12月12日上午10:48:43
* All right reserved
*/
public class ResponseBodyWrapFactoryBean implements InitializingBean{
@Autowired
private RequestMappingHandlerAdapter adapter;
@Override
public void afterPropertiesSet() throws Exception {
List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
List<HandlerMethodReturnValueHandler> handlers = new ArrayList(returnValueHandlers);
decorateHandlers(handlers);
adapter.setReturnValueHandlers(handlers);
}
private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers){
for(HandlerMethodReturnValueHandler handler : handlers){
if(handler instanceof RequestResponseBodyMethodProcessor){
ResponseBodyWrapHandler decorator = new ResponseBodyWrapHandler(handler);
int index = handlers.indexOf(handler);
handlers.set(index, decorator);
break;
}
}
}
}
6、实现具体的统一json返回处理
package cn.seisys.common;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* @author suntongxin
* Create on 2017年12月12日上午10:48:54
* All right reserved
*/
public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler{
private final HandlerMethodReturnValueHandler delegate;
public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate){
this.delegate = delegate;
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return delegate.supportsReturnType(returnType);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
RtnMsg rtnMsg = null;
if(returnValue instanceof RtnMsg){
rtnMsg = (RtnMsg)returnValue;
}else{
rtnMsg = new RtnMsg(RtnCode.STATUS_OK,"",returnValue);
}
delegate.handleReturnValue(rtnMsg, returnType, mavContainer, webRequest);;
}
}
————————————————
版权声明:本文为CSDN博主「L若儿」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/syystx/article/details/82870217
springboot统一返回json数据格式并配置系统异常拦截的更多相关文章
- MVC返回JSON数据格式书写方式
返回json数据格式,多个返回值加,隔开 [Route("api/users/web")] //如果不加这个路由请这样调用:/api/users/web?schoolname=十五 ...
- Spring统一返回Json工具类,带分页信息
前言: 项目做前后端分离时,我们会经常提供Json数据给前端,如果有一个统一的Json格式返回工具类,那么将大大提高开发效率和减低沟通成本. 此Json响应工具类,支持带分页信息,支持泛型,支持Htt ...
- 2.SpringBoot之返回json数据
一.创建一个springBoot个项目 操作详情参考:1.SpringBoo之Helloword 快速搭建一个web项目 二.编写实体类 /** * Created by CR7 on 2017-8- ...
- 美化WebApi,使其统一返回Json格式
博客部分代码来自其他博主,暂时找不到你的博文连接,如果您觉得我的代码中引入了您的代码或者文章,可在下方把您的博客文章写在下面,谢谢!!! WebApi有两种返回数据格式,一种是XML,一种是Json, ...
- SpringMVC 返回JSON数据的配置
spring-mvc-config.xml(文件名称请视具体情况而定)配置文件: <!-- 启动Springmvc注解驱动 --> <mvc:annotation-driven> ...
- 转:spring mvc返回json数据格式
转:http://www.cnblogs.com/ssslinppp/p/4675495.html <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: ...
- 上手spring boot项目(四)之springboot如何返回json数据
在springboot整合thymeleaf中,经常会在HTML页面中接收来自服务器的json数据,然后处理json数据并在页面上渲染.那么如何在服务器中返回json类型的数据呢? 1.使用@Resp ...
- SpringBoot之返回json数据
一.创建一个springBoot个项目 二.编写实体类 /** * 返回Json数据实体类 */ public class User { private int id; private String ...
- SpringBoot 02_返回json数据
在SpringBoot 01_HelloWorld的基础上来返回json的数据,现在前后端分离的情况下多数都是通过Json来进行交互,下面就来利用SpringBoot返回Json格式的数据. 1:新建 ...
随机推荐
- GitHub与Markdown(学习笔记)
一.学前提问: 1.GitHub用翻墙吗? 访问 GitHub 不用翻墙,只是可能访问速度稍慢些. 2.英语差学得会吗? GitHub 虽然都是英文,但是,对英语水平的要求不是那么高,都是些简单的单词 ...
- ipcm
用来删除一个或更多的消息队ipcm列.信号量集或者共享内存标识
- Binding a Xamarin.Forms WebView to ReactiveUI View Model using Custom Type Converters
引用:https://jamilgeor.com/binding-a-xamarin-forms-webview-to-reactiveui-view-model-using-custom-type- ...
- php保存canvas导出的base64图片
代码如下: <?php $img='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAABxCAYAAABoUdWRAAAAAXNSR0IAr ...
- gulp+webpack多页应用开发,webpack仅处理打包js
项目背景:一个综合网站,开发模式为后端嵌套数据,前端开发静态页面和部分组件. 问题:gulp任务处理自动刷新.sass编译等都是极好的.但是对于js的处理并不是很好,尤其是项目需要开发组件时候,如评论 ...
- Redis BGSAVE因为内存不足 fork 失败导致目标 Redis 无法访问的问题
中秋的时候正在外面愉快的在外卖喝着咖啡玩电脑......突发 redis 报警从 sentry 应用端曝出的错误 MISCONF Redis is configured to save RDB sna ...
- 基于python的学生管理系统(含数据库版本)
这次支持连接到后台的数据库,直接和数据库进行交互,实现基本的增删查改 #!/usr/bin/python3 # coding=utf-8 """ ************ ...
- SpringMVC自定义类型转换器
SpringMVC 自定义类型转换器 我们在使用SpringMVC时,常常需要把表单中的参数映射到我们对象的属性中,我们可以在默认的spring-servlet.xml加上如下的配置即可做到普通数据 ...
- linux服务器磁盘挂载
1.先查看当前服务器挂载的磁盘个数 fdisk -l 2.将vdb磁盘挂载到/data目录下 mount /dev/vdb /data 3.df -h 检查磁盘挂载的情况
- python爬虫 TapTap
作业要求来自于https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3075 对象 - TapTap TapTap 是一个高品质手游玩家社区, ...