In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to achieve a unified back-end return format in SpringBoot". In daily operation, I believe many people have doubts about how to achieve a unified back-end return format in SpringBoot. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to achieve a unified back-end return format in SpringBoot". Next, please follow the editor to study!
1. Why return a uniform standard format for SpringBoot
By default, there are three common return formats for SpringBoot:
1.1 returns String@GetMapping ("/ hello") public String hello () {return "hello";}
At this point, the returned value obtained by calling the API is as follows:
Hello
1.2 return the custom object @ GetMapping ("/ student") public Student getStudent () {Student student = new Student (); student.setId (1); student.setName ("didiplus"); return student;} / / student class @ Datapublic class Student {private Integer id; private String name;}
At this point, the returned value obtained by calling the API is as follows:
{"id": 1, "name": "didiplus"}
1.3 Interface exception @ GetMapping ("/ error") public int error () {int I = 9 Uniplet0; return I;}
At this point, the return value obtained by calling the API is as follows
The version of SpringBoot is v2.6.7
two。 Define the return object package com.didiplus.common.web.response;import lombok.Data;import java.io.Serializable;/** * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-24 * Desc: Ajax returns JSON result package number according to * / @ Datapublic class Result implements Serializable {/ * whether the return is successful * / private boolean success / * * error status * / private int code; / * error message * / private String msg; / * return data * / private T data; / * timestamp * / private long timest public Result () {this.timestamp = System.currentTimeMillis () } / * successful operation * / public static Result success () {return success (null);} / * with data * / public static Result success (T data) {return success (ResultCode.RC100.getMessage (), data) } / * complete exercise, with interest elimination * / public static Result success (String message) {return success (message, null) Public static Result success (String message, T data) {return success (ResultCode.RC100.getCode (), message, data) } / * completion operation with custom state code and information cancellation * / public static Result success (int code,String message) {return success (code, message, null);} public static Result success (int code,String message,T data) {Result result = new Result (); result.setCode (code); result.setMsg (message) Result.setSuccess (true); result.setData (data); return result;} / * * failure operation, default data is * / public static Result failure () {return failure (ResultCode.RC100.getMessage ()) } / * failure operation with custom message cancellation * / public static Result failure (String message) {return failure (message, null) } / * failure operation with self-defined message cancellation and data * / public static Result failure (String message, T data) {return failure (ResultCode.RC999.getCode (), message, data) } / * * failure operation with custom state code and public static Result failure (int code, String message) {return failure (ResultCode.RC999.getCode (), message, null) } / * failure operation with custom state code, information cancellation and data * / public static Result failure (int code, String message, T data) {Result result = new Result (); result.setCode (code); result.setMsg (message); result.setSuccess (false); result.setData (data) Return result;} / * Boolean return operation with default return value * / public static Result decide (boolean b) {return decide (b, ResultCode.RC100.getMessage (), ResultCode.RC999.getMessage ()) } / * Boolean return operation with custom message cancellation * / public static Result decide (boolean b, String success, String failure) {if (b) {return success (success);} else {return failure (failure);} 3. Define the status code package com.didiplus.common.web.response;import lombok.Getter / * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-24 * Desc: Unification return status code * / public enum ResultCode {/ * * Operation succeeded * * / RC100 (100, "Operation successful"), / * Operation failure * / RC999 (999, "Operation failure"), / * Service current limit * / RC200 (200,200, "Service enables current limit protection" Please try again later!), / * * Service degradation * * / RC201 (201," Service degradation protection is enabled, please try again later! "), / * hotspot parameter current limit * * / RC202 (202," hotspot parameter current limit, please try again later!"), / * * system rules do not meet * * / RC203 (203,203,Please try again later!) / * * Authorization rules do not pass * * / RC204 (204, "Authorization rules fail, please try again later!"), / * * access_denied**/ RC403 (403, "No access, please contact the administrator to grant permissions"), / * access_denied**/ RC401 (401, "exception when anonymous users access unprivileged resources"), / * Service exception * / RC500 (500) "system exception Please try again later), INVALID_TOKEN (2001, "invalid access token"), ACCESS_DENIED (2003, "do not have permission to access this resource"), CLIENT_AUTHENTICATION_FAILED (1001, "client authentication failed"), USERNAME_OR_PASSWORD_ERROR (1002, "wrong username or password"), UNSUPPORTED_GRANT_TYPE (1003, "unsupported authentication mode") / * * Custom status code * * / @ Getter private final int code; / * with message cancellation * / @ Getter private final String message; / * Constructor method * / ResultCode (int code, String message) {this.code = code; this.message = message;}} 4. Unified return format @ GetMapping ("/ hello") public Result hello () {return Result.success ("successful operation", "hello");}
At this point, the returned value obtained by calling the API is as follows:
{"success": true, "code": 100," msg ":" Operation succeeded "," data ":" hello "," timestamp ": 1650785058049}
This has indeed achieved the desired results, as I have seen in many projects, when the Controller layer wrappers the returned results through Result.success () and returns them to the front end. It seems unprofessional and not elegant. So we need to optimize the code, and the goal is not to manually define the Result return value for every interface.
5. Advanced implementation mode
To optimize this code is simple, we only need to use the ResponseBodyAdvice provided by SpringBoot.
5.1 ResponseBodyAdvice source code public interface ResponseBodyAdvice {/ * whether support advice function * true support, false does not support * / boolean supports (MethodParameter var1, Class > var2) / * process the returned data * / @ Nullable T beforeBodyWrite (@ Nullable T var1, MethodParameter var2, MediaType var3, Class > var4, ServerHttpRequest var5, ServerHttpResponse var6);}
You only need to write a concrete implementation class.
@ RestControllerAdvicepublic class ResponseAdvice implements ResponseBodyAdvice {@ Autowired ObjectMapper objectMapper; @ Override public boolean supports (MethodParameter returnType, Class > converterType) {return true;} @ SneakyThrows @ Override public Object beforeBodyWrite (Object body, MethodParameter returnType, MediaType selectedContentType, Class > selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {if (body instanceof String) {return objectMapper.writeValueAsString (ResultCode.RC100.getMessage (), body)) } return Result.success (ResultCode.RC100.getMessage (), body);}
There are two things to pay attention to:
The @ RestControllerAdvice annotation @ RestControllerAdvice is an enhancement of the @ RestController annotation and can achieve three functions:
Global exception handling
Global data binding
Global data preprocessing
5.2 String type judgment if (body instanceof String) {return objectMapper.writeValueAsString (Result.success (ResultCode.RC100.getMessage (), body));}
This code must be added. If Controller returns String directly, SpringBoot returns directly, so we need to convert it to json manually. After the above processing, we no longer need to convert through ResultData.success (), directly return to the original data format, SpringBoot automatically helps us achieve the wrapper class encapsulation.
@ GetMapping ("/ hello") public String hello () {return "hello,didiplus";} @ GetMapping ("/ student") public Student getStudent () {Student student = new Student (); student.setId (1); student.setName ("didiplus"); return student;}
At this point, the data returned by calling the API is:
{"success": true, "code": 100," msg ":" Operation succeeded "," data ":" hello,didiplus "," timestamp ": 1650786993454}
At this point, the study on "how to achieve a unified back-end return format in SpringBoot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.