为什么要统一返回值
在我们做后端应用的时候,前后端分离的情况下,我们经常会定义一个数据格式,通常会包含code,message,data这三个必不可少的信息来方便我们的交流,下面我们直接来看代码
1.需要增加的依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<lombok.version>1.18.24</lombok.version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<hutool.version>5.8.2</hutool.version>
</dependency>
</dependencies>
2.model实体
package com.example.model;
import lombok.Data;
import java.io.Serializable;
@Data
//<T>泛型返回可以为任何类型
public class HttpResponse<T> implements Serializable {
/*
* 返回码(格式内部指定)
* 0代码正常
* 非0代表错误
* */
private int code;
//返回错误信息
private String message;
private T data;
}
2.自定义注解,用于标识类是否需要统一返回值
package com.example.annotion;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoWapper {
}
3.做统一返回值的业务逻辑
package com.example.advise;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.model.HttpResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;
//扫描要做统一返回项
@RestControllerAdvice(basePackages = {"com.example.controller"})
public class MyResoonseBody implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
//找到当前执行的方法属于哪个类
Class<?> declaringClass = returnType.getDeclaringClass();
//查找该类是否有NoWapper注解
boolean b = AnnotationUtil.hasAnnotation(declaringClass, NoWapper.class);
//如果有就不用再统一封装.
if(b){
return false; //返回false就不会再进下面beforeBodyWrite方法.
}
return true;//所有都拦截
}
}
//处理异常
@ExceptionHandler(value = Exception.class)
public Object defaulErrorHander(HttpServletRequest req, Exception ex) {
HttpResponse<Object> httpResponse = new HttpResponse<>();
httpResponse.setCode(1);
httpResponse.setMessage(ex.getMessage());
return httpResponse;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
HttpResponse<Object> httpResponse = new HttpResponse<>();
//hutool初始message转换为空
String message = StrUtil.EMPTY;
httpResponse.setCode(0);
httpResponse.setMessage(message);
httpResponse.setData(body);
//处理返回类型为字符串
if(selectedConverterType == StringHttpMessageConverter.class){
//hutool JSONUtil.toJsonStr字符串转换为json数据
return JSONUtil.toJsonStr(httpResponse);
} else{
return httpResponse;
}
}
}
4.有统一返回值controller测试
package com.example.controller;
import cn.hutool.core.collection.CollUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class Demo {
@GetMapping("/test")
public String test1() {
return "么么哒";
}
@GetMapping("/test2")
public List<Integer> test2() {
// CollUtil.newArrayList hutool初始化一个集合
ArrayList<Integer> integers = CollUtil.newArrayList(1, 2, 3, 4);
return integers;
}
@GetMapping("/test3")
public String test3(){
int b=0;
int c=5/b;
return "ok";
}
}
运行结果:
5.加注解无统一返回值controller测试
package com.example.controller;
import cn.hutool.core.collection.CollUtil;
import com.example.annotion.NoWapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@NoWapper
public class NoWapperDemoController {
@GetMapping("/nowapper")
public List<Integer> test2() {
ArrayList<Integer> integers = CollUtil.newArrayList(1, 2, 3, 4);
return integers;
}
}
运行结果: