@springboot @RestControllerAdvice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import cn.focusmedia.central.common.dto.ResultDTO;
import cn.focusmedia.central.common.dto.ResultPageDTO;
import cn.focusmedia.enums.ResponseEnums;
import cn.focusmedia.utils.PageRequest;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
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.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.ArrayList;
@EnableWebMvc
@Configuration
public class UnifiedReturnConfig {
@RestControllerAdvice()
static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
/*
如果已经封装了好了,直接返回
*/
if (o instanceof ResultDTO) {
return o;
}
if (o instanceof String) {
// 用这个就报错
// return ResultDTO.build(ResponseEnums.SUCCESS.getResultCode(), (String) o, new ArrayList<String>());
ResultDTO<ArrayList<String>> build = ResultDTO.build(ResponseEnums.SUCCESS.getResultCode(), (String) o, new ArrayList<String>());
return JSON.toJSONString(build);
}
if (o instanceof PageRequest) {
ResultPageDTO<Object> pageDTO = new ResultPageDTO<>();
pageDTO.setResultCode(ResponseEnums.SUCCESS.getResultCode());
pageDTO.setResultMessage(ResponseEnums.SUCCESS.getResultMessage());
pageDTO.setItems(o);
return pageDTO;
}
return ResultDTO.build
(
ResponseEnums.SUCCESS.getResultCode(),
ResponseEnums.SUCCESS.getResultMessage(),
o
);
}
}
}