In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail the "spring boot global unified return of RESTful style data, unified exception handling method" with detailed content, clear steps and proper handling of details. I hope that this article "spring boot global unified return of RESTful style data, unified exception handling method" can help you solve your doubts.
Globally uniformly returns RESTful-style data, mainly the method of implementing the ResponseBodyAdvice interface, and modifies the return value before output.
Use the annotation @ RestControllerAdvice to intercept exceptions and handle them uniformly.
Development environment:
IntelliJ IDEA 2019.2.2
Jdk1.8
Spring Boot 2.2.2
1. Create a SpringBoot project. The dependency packages referenced by pom.xml are as follows
Org.springframework.boot spring-boot-starter-web org.projectlombok lombok true com.alibaba fastjson 1.2.62
2. Define a return class
Package com.example.response.entity;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;import java.io.Serializable;@Data@NoArgsConstructor@ToStringpublic class ResponseData implements Serializable {/ * status code: 0-success, 1-failed * * / private int code; / * error message. If successful, it can be empty or SUCCESS * * / private String msg / * return result data * * / private T data; public static ResponseData success () {return success (null);} public static ResponseData success (Object data) {ResponseData result = new ResponseData (); result.setCode (0); result.setMsg ("SUCCESS"); result.setData (data); return result } public static ResponseData fail (String msg) {return fail (msg,null);} public static ResponseData fail (String msg, Object data) {ResponseData result = new ResponseData (); result.setCode (1); result.setMsg (msg); result.setData (data); return result;}}
3. Data returned by unified intercept API
Create a new class GlobalResponseHandler, use the annotation @ RestControllerAdvice, and implement the method of the ResponseBodyAdvice interface, where the method supports can determine which ones need to be intercepted, and the method beforeBodyWrite can modify the return value before output, so as to return uniform interface data.
Package com.example.response.config;import com.alibaba.fastjson.JSON;import com.example.response.entity.ResponseData;import org.springframework.core.MethodParameter;import org.springframework.http.MediaType;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.web.bind.annotation.RestControllerAdvice;import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice / * implement the ResponseBodyAdvice interface, which can modify the returned value before output * / @ RestControllerAdvicepublic class GlobalResponseHandler implements ResponseBodyAdvice {/ / determine the supported type @ Override public boolean supports (MethodParameter methodParameter, Class > aClass) {/ / check whether the annotation exists, and ignore intercepting if (methodParameter.getDeclaringClass (). IsAnnotationPresent (IgnorReponseAdvice.class)) {return false } if (methodParameter.getMethod (). IsAnnotationPresent (IgnorReponseAdvice.class)) {return false;} return true;} @ Override public Object beforeBodyWrite (Object o, MethodParameter methodParameter, MediaType mediaType, Class > aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {/ / judge to build a ResponseData object for null and return if (o = null) {return ResponseData.success () } / / it is judged that the ResponseData subclass or itself returns Object o itself, because it is possible that the ResponseData was created when the interface returned, so avoid encapsulating if (o instanceof ResponseData) {return (ResponseData) o again. } / / String special handling, otherwise an exception if (o instanceof String) {return JSON.toJSON (ResponseData.success (o)) .toString ();} return ResponseData.success (o);}}
New Custom Annotation IgnorReponseAdvice
Package com.example.response.config;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface IgnorReponseAdvice {}
4. Unified exception handling
Package com.example.response.exception;import com.example.response.entity.ResponseData;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvicepublic class GlobalExceptionHandler {@ ExceptionHandler (Exception.class) public ResponseData exceptionHandler (Exception e) {e.printStackTrace (); return ResponseData.fail ("Server exception:" + e.getMessage ());}}
5. Create a new entity class for testing
Package com.example.response.entity;import lombok.Data;@Datapublic class User {private Long userId; private String userName; public User (Long userId, String userName) {this.userId = userId; this.userName = userName;}}
6. Create a new controller class for testing
Package com.example.response.controller;import com.example.response.config.IgnorReponseAdvice;import com.example.response.entity.ResponseData;import com.example.response.entity.User;import org.springframework.web.bind.annotation.*;import java.util.ArrayList;import java.util.List;@RestControllerpublic class DemoController {@ GetMapping ("user") public User user () {User u = new User (100L, "U1"); return u } @ GetMapping ("userList") public List userList () {List list = new ArrayList (); list.add (new User (100L, "U1")); list.add (new User (200L, "U2")); return list;} @ GetMapping ("test1") public String test1 () {return "test1" @ GetMapping ("test2") public ResponseData test2 () {return ResponseData.success ("test2");} @ IgnorReponseAdvice @ GetMapping ("test3") public String test3 () {return "test3";} @ GetMapping ("test4") public String test4 () {Integer x = 1 / 0; return x.toString () } @ GetMapping ("test5") public String test5 () throws Exception {throw new Exception ("Custom exception Information");}}
7. Test with Postman
(1) request http://localhost:8080/user and return
{"code": 0, "msg": "SUCCESS", "data": {"userId": 100, "userName": "U1"}}
(2) request http://localhost:8080/userList and return
{"code": 0, "msg": "SUCCESS", "data": [{"userId": 100, "userName": "U1"}, {"userId": 200, "userName": "U2"}]}
(3) request http://localhost:8080/tes1 and return
{"msg": "SUCCESS", "code": 0, "data": "test1"}
(4) request http://localhost:8080/test2 and return
{"code": 0, "msg": "SUCCESS", "data": "test2"}
(5) request http://localhost:8080/test3 and return
Test3
(6) request http://localhost:8080/test4 and return
{"code": 1, "msg": "Server exception: / by zero", "data": null}
(7) request http://localhost:8080/test5 and return
{"code": 1, "msg": "Server exception: custom exception information", "data": null} so far, the article "spring boot globally uniformly returns RESTful-style data and unified exception handling" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself before you can understand it. If you want to know more about related articles, Welcome to the industry information channel.
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.