背景
相信大部分后端开发人员在日常开发中都需要和前端对接,当然前后端都是你自己一个人搞的话可以想怎么玩就怎么玩,但是我们还是要做到一定的规范性。在前后端分离的项目中后端返回的格式一定要友好,并且固定,不能经常变来变去,不然会对前端的开发人员带来很多的工作量。
SpringBoot Controller 常见的返回格式
String
@PostMapping("/test") public String test(){ return "Hello World"; }
postman调用结果:
自定义对象
正常返回
@PostMapping("/getUser") public ActionResult getUser(){ User user = new User(); user.setId(UUID.randomUUID().toString()); user.setName("MrDong"); user.setAge(20); return ActionResult.defaultOk(user); }
postman调用结果:
错误返回
@PostMapping("/error") public ActionResult error(){ return ActionResult.defaultFail(1000,"服务器异常,请联系管理员"); }
postman调用结果:
定义返回对象
我定义两个ActionResult这个对象来对返回值进行封装,可以根据自己公司实际情况修改:
package com.wxd.entity; import com.wxd.enums.ResultCodeEnum; import lombok.Data; /** * @ClassName ActionResult * @Description 统一返回值封装 * @Author Mr Dong * @Date 2022/7/26 14:51 */ @Data public class ActionResult { private Integer code; private String msg; private Integer count; private Object data; public static ActionResult defaultOk(Integer code, String msg, Integer count, Object data) { return new ActionResult(code, msg, count, data); } public static ActionResult defaultOk(Integer count, Object data) { return new ActionResult(ResultCodeEnum.RC200, count, data); } public static ActionResult defaultOk(Object data) { return new ActionResult(ResultCodeEnum.RC200, null, data); } public static ActionResult defaultOk() { return new ActionResult(ResultCodeEnum.RC200); } public static ActionResult defaultFail() { return new ActionResult(ResultCodeEnum.RC999); } public static ActionResult defaultFail(Integer code, String msg) { return new ActionResult(code, msg); } public static ActionResult defaultFail(ResultCodeEnum resultCodeEnum) { return new ActionResult(resultCodeEnum); } public ActionResult(Integer code, String msg, Integer count, Object data) { this.code = code; this.msg = msg; this.count = count; this.data = data; } public ActionResult(Integer code, String msg) { this.code = code; this.msg = msg; } public ActionResult(ResultCodeEnum resultCodeEnum) { this.code = resultCodeEnum.getCode(); this.msg = resultCodeEnum.getMessage(); } public ActionResult(ResultCodeEnum resultCodeEnum, Integer count, Object data) { this.code = resultCodeEnum.getCode(); this.msg = resultCodeEnum.getMessage(); this.count = count; this.data = data; } }
定义状态枚举
package com.wxd.enums; /** * @author wxd * @version V1.0 * @description ResultCodeEnum * @date 2022/8/10 13:35 **/ public enum ResultCodeEnum { /** * 操作成功 */ RC200(200, "操作成功"), /** * 未授权 */ RC401(401, "用户未授权"), /** * 请求被禁止 */ RC403(403, "请求被禁止"), /** * 服务异常 */ RC500(500, "服务器异常,请联系管理员"), /** * 操作失败 */ RC999(999, "操作失败"), RC1001(1001, "用户名密码错误"), RC1002(1002, "未授权的资源"), RC1003(1003, "未授权的资源"), RC1004(1004, "缺少请求参数异常"), RC1005(1005, "缺少请求体参数异常"), RC1006(1006, "参数绑定异常"), RC1007(1007, "方法参数无效异常"); private Integer code; private String message; ResultCodeEnum(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public String getMessage() { return message; } }
统一处理返回值及异常
实现原理:需要实现SpringBoot提供的ResponseBodyAdvice这个接口,完成统一返回值的封装及异常的处理。实现了这个接口之后,在Controller返回的时候只需要将对象直接返回,有些不需要返回值的可以直接返回void。
package com.wxd.advice; import com.wxd.entity.ActionResult; import com.wxd.enums.ResultCodeEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; /** * @version: V1.0 * @author: wxd * @description: 全局异常处理以及返回值的统一封装 * @Date 2022/7/26 16:24 */ @RestControllerAdvice(value = "com.wxd.controller") @Slf4j public class ResponseAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Class aClass) { return true; } /** * 统一包装 * * @param o * @param methodParameter * @param mediaType * @param aClass * @param serverHttpRequest * @param serverHttpResponse * @return */ @Override public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { /** * String、ActionResult不需要再包一层(不想包一层ActionResult对象的可以在这里把这个对象过滤掉) */ if (o instanceof String || o instanceof ActionResult) { return o; } return ActionResult.defaultOk(o); } /** * 系统内部异常捕获 * * @param e * @return */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = Exception.class) public Object exceptionHandler(Exception e) { log.error("系统内部异常,异常信息", e); return ActionResult.defaultFail(ResultCodeEnum.RC500); } /** * 忽略参数异常处理器;触发例子:带有@RequestParam注解的参数未给参数 * * @param e 忽略参数异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) public Object parameterMissingExceptionHandler(MissingServletRequestParameterException e) { log.error("缺少Servlet请求参数异常", e); return ActionResult.defaultFail(ResultCodeEnum.RC1004); } /** * 缺少请求体异常处理器;触发例子:不给请求体参数 * * @param e 缺少请求体异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) public Object parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) { log.error("参数请求体异常", e); return ActionResult.defaultFail(ResultCodeEnum.RC1005); } /** * 统一处理请求参数绑定错误(实体对象传参); * * @param e BindException * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(BindException.class) public Object validExceptionHandler(BindException e) { log.error("方法参数绑定错误(实体对象传参)", e); return ActionResult.defaultFail(ResultCodeEnum.RC1006); } /** * 统一处理请求参数绑定错误(实体对象请求体传参); * * @param e 参数验证异常 * @return ResponseResult */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({MethodArgumentNotValidException.class}) public Object parameterExceptionHandler(MethodArgumentNotValidException e) { log.error("方法参数无效异常(实体对象请求体传参)", e); return ActionResult.defaultFail(ResultCodeEnum.RC1007); } }
void 无返回值
有返回值
以上是如何处理SpringBoot统一返回格式的详细内容。更多信息请关注PHP中文网其他相关文章!

本文讨论了使用Maven和Gradle进行Java项目管理,构建自动化和依赖性解决方案,以比较其方法和优化策略。

本文使用Maven和Gradle之类的工具讨论了具有适当的版本控制和依赖关系管理的自定义Java库(JAR文件)的创建和使用。

本文讨论了使用咖啡因和Guava缓存在Java中实施多层缓存以提高应用程序性能。它涵盖设置,集成和绩效优势,以及配置和驱逐政策管理最佳PRA

本文讨论了使用JPA进行对象相关映射,并具有高级功能,例如缓存和懒惰加载。它涵盖了设置,实体映射和优化性能的最佳实践,同时突出潜在的陷阱。[159个字符]

Java的类上载涉及使用带有引导,扩展程序和应用程序类负载器的分层系统加载,链接和初始化类。父代授权模型确保首先加载核心类别,从而影响自定义类LOA


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Dreamweaver CS6
视觉化网页开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

SublimeText3 Linux新版
SublimeText3 Linux最新版