SpringBoot定义统一的controller返回格式

本文介绍了如何在Spring MVC中定义一个自定义的响应包装类`Response`,并实现`ResponseBodyAdvice`接口来对Controller返回的数据进行二次封装。在`ApiResponseBody`类中,当Controller返回字符串时,进行了特殊处理,避免了类型转换异常。通过这种方式,可以统一处理和增强API的响应格式。
摘要由CSDN通过智能技术生成

一.定义接口返回包装类

package com.example.auth.filter;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Response<T> {

    private int code;
    private String msg;
    private T data;

    public static <T> Response<T> ok(T data) {
        int okCode = 200;
        return new Response<>(okCode, "请求成功", data);
    }
}

 2、编写ResponseBodyAdvice接口实现

(controller的值返回成功后会走这里的方法,对结果进行二次封装。@RestControllerAdvice注解和ResponseBodyAdvice接口实现统一处理controller返回

package com.example.auth.config;

import com.alibaba.fastjson.JSON;
import com.example.auth.filter.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
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;

@RestControllerAdvice(basePackages = "com.example.auth.provider.controller")
public class ApiResponseBody implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType
            , Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 防止二次封装
        if (body instanceof Response) {
            return body;
        }

		// 处理controller返回为字符串时, 转换报异常的bug(默认使用的jackson转换器会报类型转换的错,感兴趣可以跟下源代码)
		//(如果使用FastJsonHttpMessageConverter,则不需要加下面if判断)
        if (body instanceof String) {
            return JSON.toJSONString(Response.ok(body));
        }
        
        return Response.ok(body);
    }
}

3.controller编写

package com.example.auth.provider.controller;

import com.example.auth.provider.model.User;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.soap.SOAPBinding;


@RestController
@Api(tags = {"接口鉴权"})
@RequestMapping(value = "/authentication")
public class UserController {

    @PostMapping("/getUser")
    public User getUser(int id) {
        User user1 = new User(1, "王云召");
        User user2 = new User(2, "王云盼");
        User user3 = new User(3, "啥也不是");
        User user4= new User();
        if (id == user1.getId()) {
            return user1;
        } else if (id == user2.getId()) {
            return user2;
        }
        return user4;
    }

}

4.结果

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值