Naming of 1 url
In the actual development, nouns are in the majority.
- Get to get data
- post adds data
- put modifies data
- delete logical false deletion
2 Format of returned data
2.1 Generally, json data {status code: information} is returned.
** Some commonly used return status codes**
https://help.aliyun.com/knowledge_detail/36393.html?spm=5176.10695662.1996646101.searchclickresult.33f71bb4EstSUR&aly_as=Gf1sQix
2.2 Call static methods directly in Controller
2.2.1 First create an interface for the return set
public interface Result<T> { }
2.2.2 define return information enumeration type
public enum StatusTypeEnum { /** * 200 For success * 404 For error messages */ SUCCESS(200,"success"), ERROR(404,"error"); private String msg; private int status; StatusTypeEnum(int status, String msg) { this.status = status; this.msg = msg; } }
2.2.3 Create successResult Return Set Inheritance Return Set Interface
@Data @AllArgsConstructor @NoArgsConstructor public class SuccessResult<T> implements Result<T> { private StatusTypeEnum status; private T data; public static SuccessResult succes() { return new SuccessResult<>(StatusTypeEnum.SUCCESS, null); } public static <T> SuccessResult succes(T data) { return new SuccessResult<>(StatusTypeEnum.SUCCESS, data); } }
2.2.4 Create errorResult Return Set Inheritance Return Set Interface
@Data @NoArgsConstructor @AllArgsConstructor public class ErrorResult implements Result { private StatusTypeEnum status; private String msg; public static ErrorResult error(int status, Exception ex) { return new ErrorResult(StatusTypeEnum.ERROR, ex.getMessage()); } public static ErrorResult error() { return new ErrorResult(StatusTypeEnum.ERROR, "error"); } }
The content of the definition needs to be determined according to the business. This is only the general framework.
2.3 Using AOP section to become
@ RestController Advice + Implementation of ResponseBodyAdvice
Encapsulating Result into aop, the Controller layer returns parameters directly to AOP to determine and return Result
@RestControllerAdvice @Slf4j public class GlobalResultAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter returnType, Class converterType) { log.error("supports"); //For false, the following aop method will not be executed return true; } /** * * @param body * @param returnType * @param selectedContentType * @param selectedConverterType * @param request * @param response * @return */ @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Object resp = null; if (body instanceof SuccessResult){ resp = body; }else{ resp = SuccessResult.succes(body); } return resp; } }