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:新建 ...
随机推荐
- 网站安全DDOS攻击及监测
一. 监测 在类Unix系统中可以使用top查看系统资源.进程.内存占用等信息.查看网络状态可以使用netstat.nmap等工具.若要查看实时的网络流量,监控TCP/IP连接等,则可以使用iftop ...
- websocket简单样例
服务端 var server = require('ws').Server; }); serv.on('connection',function(socket){ socket.send('hello ...
- 猎豹全球智库执行院长:中国App出海的三大规律和最具代表的五大垂直品类
https://36kr.com/p/5100078 中国出海还是处于一个黄金时代. “国内互联网公司的竞争越来越白热化,出海的时间点变得越来越紧迫,”在36氪日前举办的“WISEx新出海行业峰会”上 ...
- session内置对象
SimpleDateFormat sdf = new SimpleDateFormat(yyyy年MM月dd日) //处理日期格式 session.getCreationDate() 是获取sess ...
- Python的可变类型和不可变类型?
Python的每个对象都分为可变和不可变可变:列表.字典 不可变:数字.字符串.元组
- C++ socket bind() 函数绑定错误
VS2015编译错误: errorCxxxx: 'initializing' : cannot convert from 'std::_Bind<false,void,SOCKET&,s ...
- C# VS 调试 动态加载的 DLL
原文:https://www.cnblogs.com/DasonKwok/p/10510218.html 在这篇文章的底部,有提供示例的Demo,可以参考一下哦,拿来直接就可以运行. 说明: 编译类库 ...
- 微信小程序电影模板
[外链图片转存失败(img-STw401rR-1565101469846)(https://upload-images.jianshu.io/upload_images/11158618-52efd0 ...
- MSSQL手工注入 报错注入方法
例子:www.kfgtfcj.gov.cn/lzygg/Zixun_show.aspx?id=1[1]首先爆版本:http://www.kfgtfcj.gov.cn/lzygg/Zixun_show. ...
- 基于python的学生管理系统(含数据库版本)
这次支持连接到后台的数据库,直接和数据库进行交互,实现基本的增删查改 #!/usr/bin/python3 # coding=utf-8 """ ************ ...