重庆做网站制作公司,永久网站推广,wordpress痞子,泉州seo按天扣费在web开发中#xff0c;规范所有请求响应类型#xff0c;不管是对前端数据处理#xff0c;还是后端统一数据解析都是非常重要的。今天我们简单的方式实现如何实现这一效果
实现方式 定义响应类型
public class ResponseResultT {private static final String SUC…在web开发中规范所有请求响应类型不管是对前端数据处理还是后端统一数据解析都是非常重要的。今天我们简单的方式实现如何实现这一效果
实现方式 定义响应类型
public class ResponseResultT {private static final String SUCCESS_CODE 000;private static final String FAILURE_CODE 999;private String code;private String message;private T data;public static T ResponseResultT ok(T data){ResponseResult responseResult new ResponseResult();responseResult.setCode(SUCCESS_CODE);responseResult.setData(data);return responseResult;}public static ResponseResult fail(String code, String message){if( code null ){code FAILURE_CODE;}ResponseResult responseResult new ResponseResult();responseResult.setCode(code);responseResult.setMessage(message);return responseResult;}public static ResponseResult fail(String message){return fail(FAILURE_CODE, message);}
}定义统一的异常处理流程通过RestControllerAdvice与ExceptionHandler注解可以对Controller中的异常统一处理
RestControllerAdvice
public class ControllerAdviceHandle {ExceptionHandler(Exception.class)public ResponseResult handleException(Exception exception) {BusException busException;if (exception instanceof BusException asException) {busException asException;} else {busException convertException(exception);}return ResponseResult.fail(busException.getCode(), busException.getMessage());}
} 定义统一响应拦截通过是实现接口ResponseBodyAdvice这里可以和上面的异常一起处理
public class ControllerAdviceHandle implements ResponseBodyAdvice {Overridepublic boolean supports(MethodParameter returnType, Class converterType) {return true;}Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,ServerHttpRequest request, ServerHttpResponse response) {if( body instanceof ResponseResult){return body;}return ResponseResult.ok(body);}
}定义spring配置实现自动装配
在resource目录添加自动注入配置META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports这样通过引入jar就可以自动使用该配置
cn.cycad.web.response.ResponseConfig应用示例 比如现在有一个User实体我们通过继承基类
RestController
RequestMapping(/test)
public class TestController {GetMapping(/{val})public Object get(PathVariable(val) String val) throws BusException {if( 1.equals(val) ){throw new BusException(参数错误);}return Map.of(val,val);}}通过调用请求可以看到不管是否异常结果都是下面的格式
{code: 999,message: null,data: null
}