本文主要是介绍springboot 统一结果响应,统一异常处理,统一请求参数非空校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、统一结果响应
1.1、ResultCodeEnum
package com.nrxt.nms.mon.pt.cascade.common;import lombok.AllArgsConstructor;
import lombok.Getter;@AllArgsConstructor
@Getter
public enum ResultCodeEnum {SUCCESS(200, "成功"),FAIL(500, "失败");private Integer code;private String msg;}
1.2、Result
package com.nrxt.nms.mon.pt.cascade.common;import lombok.Data;@Data
public class Result<T> {private Integer code;private String msg;private T data;private Integer total;
}
1.3、ResultVO
package com.nrxt.nms.mon.pt.cascade.common;public class ResultVO {/*** 成功** @return*/public static Result success() {Result result = new Result();result.setCode(ResultCodeEnum.SUCCESS.getCode());result.setMsg(ResultCodeEnum.SUCCESS.getMsg());return result;}/*** 成功返回数据** @param data* @param <T>* @return*/public static <T> Result<T> success(T data) {Result result = new Result();result.setCode(ResultCodeEnum.SUCCESS.getCode());result.setMsg(ResultCodeEnum.SUCCESS.getMsg());result.setData(data);return result;}/*** 成功返回数据,总条数** @param data* @param total* @param <T>* @return*/public static <T> Result<T> success(T data, int total) {Result result = new Result();result.setCode(ResultCodeEnum.SUCCESS.getCode());result.setMsg(ResultCodeEnum.SUCCESS.getMsg());result.setData(data);result.setTotal(total);return result;}/*** 失败** @return*/public static Result fail() {Result result = new Result();result.setCode(ResultCodeEnum.FAIL.getCode());result.setMsg(ResultCodeEnum.FAIL.getMsg());return result;}/*** 失败信息** @param message* @return*/public static Result fail(String message) {Result result = new Result();result.setCode(ResultCodeEnum.FAIL.getCode());result.setMsg(message);return result;}
}
1.4、NmsPtAppController
package com.nrxt.nms.mon.pt.cascade.controller;@RestController
@RequestMapping(value = "/appmonitor/ptcas")
public class NmsPtAppController {private static final Logger logger = Logger.getLogger(NmsPtAppController.class);@ResourceNmsPtAppService nmsPtAppService;/*** 系统级联监控查询** @param nmsAppMonitorQuery* @return*/@PostMapping("/queryFilterAppMonitor")public Result queryFilterAppMonitor(@RequestBody NmsAppMonitorQuery nmsAppMonitorQuery) {List<NmsAppMonitorDO> nmsAppMonitorDOList = nmsPtAppService.queryFilterAppMonitor(nmsAppMonitorQuery);return ResultVO.success(nmsAppMonitorDOList);}
}
2、统一异常处理
3、统一请求参数非空校验
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
这篇关于springboot 统一结果响应,统一异常处理,统一请求参数非空校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!