Restful风格常用的响应结果总结

通常在我们构建Controller层的Restful接口的时候,需要统一返回一定格式的数据,下面是在项目中用到的格式的一个简单的总结 

 1. ResultData:

package cn.cuit.datas.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.fasterxml.jackson.annotation.JsonIgnore;


/**
 * 返回数据
 */
public class ResultData implements Serializable
{

	public static String SUCCESS = "S";
	public static String FAILURE = "F";

	private String result;

	private String message;

	@JsonIgnore
	private final boolean validError = false;

	@JsonIgnore
	private List validMsg = new ArrayList();

	/**
	 * 接口数据
	 */
	private Object data;

	private static final long serialVersionUID = -3235957810592174380L;

	public static ResultData successResult()
	{
		return new ResultData(null, true, null);
	}

	public static ResultData successResult(final String msg)
	{
		return new ResultData(msg, true, null);
	}

	public static ResultData successResult(final Object data)
	{
		return new ResultData(null, true, data);
	}

	public static ResultData successResult(final String msg, final Object data)
	{
		return new ResultData(msg, true, data);
	}

	public static ResultData failureResult()
	{
		return new ResultData(null, false, null);
	}

	public static ResultData failureResult(final String msg)
	{
		return new ResultData(msg, false, null);
	}

	public static ResultData failureResult(final String msg, final Object data)
	{
		return new ResultData(msg, false, data);
	}

	public static ResultData failureResult(final BindingResult bindingResult)
	{
		return new ResultData(getErrorMessage(bindingResult), false, null);
	}

	public ResultData(final String msg, final boolean success, final Object data)
	{
		super();
		this.message = msg;
		this.data = data;

		if (success)
		{
			this.setResult(SUCCESS);
		}
		else
		{
			this.setResult(FAILURE);
		}
	}

	public String getResult()
	{
		return result;
	}

	public void setResult(final String result)
	{
		this.result = result;
	}

	public String getMessage()
	{
		if (StringUtils.isNotBlank(message))
		{
			return message;
		}
		if (this.isValidError())
		{
			return this.validMsg.get(0).getObjectName() + " " + this.validMsg.get(0).getDefaultMessage();
		}
		if (this.isSuccessful())
		{
			return "操作成功";
		}
		return message;
	}

	public void setMessage(final String msg)
	{
		this.message = msg;
	}

	public Object getData()
	{
		return data;
	}

	public void setData(final Map data)
	{
		this.data = data;
	}


	public List getValidMsg()
	{
		return validMsg;
	}

	@JsonIgnore
	public boolean isSuccessful()
	{
		return SUCCESS.equals(this.result);
	}


	public boolean isValidError()
	{

		return this.validMsg.size() > 0;
	}

	public void setValidMsg(final List validMsg)
	{
		this.validMsg = validMsg;
	}

	public void buildValidMsg(final FieldError objectError)
	{

		this.validMsg.add(new ValidMsgObject(objectError.getDefaultMessage(), objectError.getObjectName(), objectError.getField()));
	}

	public void buildValidMsg(final String defaultMessage, final String objectName, final String field)
	{

		this.validMsg.add(new ValidMsgObject(defaultMessage, objectName, field));
	}


	private static class ValidMsgObject implements Serializable
	{
		private static final long serialVersionUID = -6083742869733837683L;
		String defaultMessage;
		String objectName;
		String field;

		public ValidMsgObject(final String defaultMessage, final String objectName, final String field)
		{
			super();
			this.defaultMessage = defaultMessage;
			this.objectName = objectName;
			this.field = field;
		}

		@SuppressWarnings("unused")
		public String getDefaultMessage()
		{
			return defaultMessage;
		}

		@SuppressWarnings("unused")
		public void setDefaultMessage(final String defaultMessage)
		{
			this.defaultMessage = defaultMessage;
		}

		@SuppressWarnings("unused")
		public String getObjectName()
		{
			return objectName;
		}

		@SuppressWarnings("unused")
		public void setObjectName(final String objectName)
		{
			this.objectName = objectName;
		}

		@SuppressWarnings("unused")
		public String getField()
		{
			return field;
		}

		@SuppressWarnings("unused")
		public void setField(final String field)
		{
			this.field = field;
		}


	}

	public static String getErrorMessage(BindingResult bindingResult){
		StringBuilder messageBuilder = new StringBuilder();
		for (Iterator iterator = bindingResult.getFieldErrors().iterator(); iterator.hasNext();){
			FieldError fieldError = iterator.next();
			messageBuilder.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage());
			if(iterator.hasNext()){
				messageBuilder.append(";");
			}else {
				messageBuilder.append(".");
			}
		}
		return messageBuilder.toString();
	}
}

响应格式为:

{
    "result": "S",
    "message": "操作成功",
    "data": {...}
}

2. ResponseData:

 

package cn.cuit.datas.response;

import  cn.cuit.datas.enums.StatusCode;

import java.io.Serializable;


public class ResponseData implements Serializable{

    private Integer code;
    private String msg;
    private T data;

    public ResponseData() {
    }

    public ResponseData(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResponseData(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponseData(StatusCode statusCode) {
        this.code = statusCode.getCode();
        this.msg = statusCode.getMsg();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

package cn.cuit.datas.enums;
 
public enum  StatusCode {

    Success(0,"成功"),
    Fail(-1,"失败"),
    InvalidParams(400,"无效的参数"),
    ItemNotExist(201,"商品不存在!");
	//XXXNotExist(202, "XXX不存在")
	// ServerError(500, "服务器错误")
	//....

    private Integer code;
    private String msg;

    StatusCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

 响应格式为:

{
    "code": 0,
    "msg": "成功",
    "data": {...}
}

3. org.springframework.http.ResponseEntity

例子:

@RestController
@RequestMapping("category")
public class CategoryController {
 
    @Autowired
    private CategoryService categoryService;
 
    @GetMapping("list")
    public ResponseEntity> queryByParentId(@RequestParam(value = "pid",defaultValue = "0") Long pid){
        List categories = this.categoryService.queryByParentId(pid);
        if (CollectionUtils.isNotEmpty(categories)) {
            //返回数据就为http响应体内容,还可以添加响应头和状态码等,ok()方法实际就指定了状态码
            return ResponseEntity.ok(categories);
        }
        //返回响应状态码204
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

 ********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

你可能感兴趣的:(Java)