当前位置:   article > 正文

springboot 自定义返回值处理器HandlerMethodReturnValueHandler_springboot自定义返回封装类 handlermethodreturnvaluehandler

springboot自定义返回封装类 handlermethodreturnvaluehandler

WEB开发中有这样的需求: 返回给前台的数据需要有统一格式。但是在controller的每个mapping中手写包装很是麻烦,所以可以自定义返回值处理器进行结果包装。

返回给前台的消息格式

package net.mshome.twisted.tmall.common;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.mshome.twisted.tmall.enumeration.ErrorCode;

/**
 * 返回给前台的消息包装类
 *
 * @author tangjizhouchn@foxmail.com
 * @date 2019-08-18
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ResultWrapper<T> {
   

	@Builder.Default
    private int code = ErrorCode.OK.getValue();
	
	@Builder.Default
    private String message = "操作成功";

    private T result;

}

  • 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

自定义的返回值处理器

package net.mshome.twisted.tmall.handler;

import net.mshome.twisted.tmall.common.ResultWrapper;
import net.mshome.twisted.tmall.exception.TmallException;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/799262
推荐阅读
相关标签
  

闽ICP备14008679号