spring boot 拦截返回值并进行包装

Spring Boot 3.1.10

JAVA 17

---

 

序章

统一接口的返回值格式:ResultVO 对象。

拦截 Controller 的请求,对于 返回值不是 ResultVO 对象的,包装成 ResultVO 对象,返回 null(void) 的除外。

 

实现方式

接口 ResponseBodyAdvice

+

注解 @ControllerAdvice

 

代码:ResponseBodyProcess.java

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
@Slf4j
public class ResponseBodyProcess implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (Objects.isNull(body)) {
            return body;
        } else if (body instanceof ResultVO) {
            log.trace("todo del return body={}, uri={}", body, request.getURI());
        } else {
            log.debug("重新包装返回值 body:class={}", body.getClass());
            return ResultVO.success(AppConstant.REQUEST_OK, body);
        }
        return body;
    }
}

 

进一步:配置 MessageConverters

接口 WebMvcConfigurer

方法 void configureMessageConverters(List<HttpMessageConverter<?>> converters)。

返回 String 时,会报 异常。

解释见 参考文档#2

 

默认的 converters:

converters=[
org.springframework.http.converter.ByteArrayHttpMessageConverter@141aba65, 
org.springframework.http.converter.StringHttpMessageConverter@b5312df, 
org.springframework.http.converter.StringHttpMessageConverter@3356ff58, 
org.springframework.http.converter.ResourceHttpMessageConverter@b55f5b7, 
org.springframework.http.converter.ResourceRegionHttpMessageConverter@2aa6bbad, 
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@6b2ef50e, 
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4300e240, 
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@6f867b0c
]

ben发布于博客园

代码:AppWebConfig.java

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AppWebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 配合 ResponseBodyProcess 使用:返回 String 时
        converters.add(0, new MappingJackson2HttpMessageConverter());
    }

}

ben发布于博客园

测试接口

代码:

TestController.java
 @RestController
@RequestMapping("api/test")
@Slf4j
public class TestController {

    @GetMapping("get/string")
    public String get() {
        log.info("getString");
        return "abc";
    }

    @GetMapping("get/void")
    public void getVoid() {
        log.info("getVoid");
    }

    @GetMapping("get/int")
    public int getInt() {
        log.info("getInt");
        return 1000;
    }

    @GetMapping("get/boolean")
    public boolean getBoolean() {
        log.info("getBoolean");
        return true;
    }

    @GetMapping("get/int/ex")
    public int getIntEx() {
        log.info("getInt");
        long ex = 123/0;
        return 1000;
    }

}

 

补充说明

1、对于 登录、退出登录 等 不是 Controller 中的接口,不能拦截。

2、除了 @ControllerAdvice 注解,还有一个 @RestControllerAdvice 注解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
    // ...
}

3、interface ResponseBodyAdvice<T>

源码说明:

Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method

but before the body is written with an HttpMessageConverter.

Implementations may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver

or more likely annotated with @ControllerAdvice in which case they will be auto-detected by both.
Since: 4.1
Author: Rossen Stoyanchev

 

---END---

 

本文链接:

https://www.cnblogs.com/luo630/p/18147317

ben发布于博客园

参考资料

1、spring boot 拦截器请求返回值 springboot拦截controller返回值
https://blog.51cto.com/u_14230/6286912

2、ResponseBodyAdvice、String返回值报cannot be cast to java.lang.String的解决办法
勤而思
于 2021-06-30 18:33:07 发布
https://blog.csdn.net/wen1652166675/article/details/118367098

3、

 

ben发布于博客园

ben发布于博客园

 

posted @ 2024-04-21 20:02  快乐的欧阳天美1114  阅读(633)  评论(0编辑  收藏  举报