提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.web.core.handler; |
H |
2 |
|
|
3 |
import com.iailab.framework.common.pojo.CommonResult; |
|
4 |
import com.iailab.framework.web.core.util.WebFrameworkUtils; |
|
5 |
import org.springframework.core.MethodParameter; |
|
6 |
import org.springframework.http.MediaType; |
|
7 |
import org.springframework.http.server.ServerHttpRequest; |
|
8 |
import org.springframework.http.server.ServerHttpResponse; |
|
9 |
import org.springframework.http.server.ServletServerHttpRequest; |
|
10 |
import org.springframework.web.bind.annotation.ControllerAdvice; |
|
11 |
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; |
|
12 |
|
|
13 |
/** |
|
14 |
* 全局响应结果(ResponseBody)处理器 |
|
15 |
* |
|
16 |
* 不同于在网上看到的很多文章,会选择自动将 Controller 返回结果包上 {@link CommonResult}, |
|
17 |
* 在 onemall 中,是 Controller 在返回时,主动自己包上 {@link CommonResult}。 |
|
18 |
* 原因是,GlobalResponseBodyHandler 本质上是 AOP,它不应该改变 Controller 返回的数据结构 |
|
19 |
* |
|
20 |
* 目前,GlobalResponseBodyHandler 的主要作用是,记录 Controller 的返回结果, |
|
21 |
* 方便 {@link com.iailab.framework.apilog.core.filter.ApiAccessLogFilter} 记录访问日志 |
|
22 |
*/ |
|
23 |
@ControllerAdvice |
|
24 |
public class GlobalResponseBodyHandler implements ResponseBodyAdvice { |
|
25 |
|
|
26 |
@Override |
|
27 |
@SuppressWarnings("NullableProblems") // 避免 IDEA 警告 |
|
28 |
public boolean supports(MethodParameter returnType, Class converterType) { |
|
29 |
if (returnType.getMethod() == null) { |
|
30 |
return false; |
|
31 |
} |
|
32 |
// 只拦截返回结果为 CommonResult 类型 |
|
33 |
return returnType.getMethod().getReturnType() == CommonResult.class; |
|
34 |
} |
|
35 |
|
|
36 |
@Override |
|
37 |
@SuppressWarnings("NullableProblems") // 避免 IDEA 警告 |
|
38 |
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, |
|
39 |
ServerHttpRequest request, ServerHttpResponse response) { |
|
40 |
// 记录 Controller 结果 |
|
41 |
WebFrameworkUtils.setCommonResult(((ServletServerHttpRequest) request).getServletRequest(), (CommonResult<?>) body); |
|
42 |
return body; |
|
43 |
} |
|
44 |
|
|
45 |
} |