当前位置:   article > 正文

spring boot统一返回_springboot统一信息返回

springboot统一信息返回

springboot 写controller层代码,尽量减少重复代码,用ResponseBodyAdvice实现统一返回:

1. ResponseAdvice

package com.zdxf.common;

import com.zdxf.common.pojo.ResultVO;
import com.zdxf.common.utils.RestResponse;
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;

/**
 * @Author: zj
 * @Date: 2023/7/24 0024 17:08
 * @Description:
 */
@RestControllerAdvice(basePackages = "com.xxx.modules")
public class ResponseAdvice 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) {
        // 提供一定的灵活度,如果body已经被包装了,就不进行包装
        if (body instanceof ResultVO) {
            return body;
        }
        return ResultVO.success(body);
    }
}

  • 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

2.例子

@GetMapping("/list")
@ApiOperation(value = "分页查询列表", notes = "分页查询列表")
public Page<SysUserEntity> list(SysUserDto dto) {
 return sysUserService.queryPage(dto);
}
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/183982?site
推荐阅读
相关标签
  

闽ICP备14008679号