1. 程式人生 > 實用技巧 >springboot 響應標準設計及實現

springboot 響應標準設計及實現

背景分析

在基於C/S架構的程式設計模型中,客戶端往往需要對服務端返回的資料,基於狀態的不同進行不同的處理。例如,正確的狀態資料一種呈現方式,錯誤的狀態資料是另外一種呈現方式。於是服務端響應資料的標準化設計油然而生。

響應標準設計

在響應資料標準化設計時,首先要對響應資料進行分析,哪些資料要響應到客戶端,對這些資料進行怎樣的狀態設計等。假如現在響應的業務資料包含三部分:狀態,訊息,具體資料。我們可以這樣設計,例如:

package com.cy.pj.common.pojo;

/**
 * 基於此物件封裝服務端響應到客戶端的資料
 */
public class ResponseResult {
    /**響應狀態碼(有的人用code)*/
    private Integer state=1;//1表示ok,0表示error,.....
    /**狀態碼對應的資訊*/
    private String message="ok";
    /**正確的響應資料*/
    private Object data;

    public ResponseResult(){}

    public ResponseResult(String message){//new ResponseResult("delete ok"),
        this.message=message;
    }
    public ResponseResult(Object data){//new ResponseResult(list);
        this.data=data;
    }
    public ResponseResult(Throwable e){//new ResponseResult(e);
        this.state=0;
        this.message=e.getMessage();
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

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

    public Object getData() {
        return data;
    }

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

響應資料的封裝

在Controller類的邏輯方法中進行正常的響應資料封裝,例如:

package com.cy.pj.module.controller;

import com.cy.pj.common.pojo.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ArithmeticController {

      @RequestMapping("/doCompute/{n1}/{n2}")
      public ResponseResult doCompute(@PathVariable  Integer n1, @PathVariable Integer n2){
          Integer result=n1/n2;
          ResponseResult r=new ResponseResult("計算結果:"+result);
          r.setData(result);
          return r;
      }
}

在全域性異常處理物件中進行異常響應資料的封裝,例如:

package com.cy.pj.common.web;

import com.cy.pj.common.pojo.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestControllerAdvice
public class GlobalExceptionHandler {
      private static final Logger log= LoggerFactory.getLogger(GlobalExceptionHandler.class);//2
      @ExceptionHandler(ArithmeticException.class)
      public ResponseResult doHandleArithmeticException(ArithmeticException e){
          e.printStackTrace();
          log.info("exception {}",e.getMessage());
          return new ResponseResult(e);//封裝異常結果
      }
}

總結(Summary)

本小節主要講解了Spring Boot工程中對邏輯資料的響應如何進行標準化設計,為什麼這樣設計,這樣設計的好處以及如何設計。通過對這一小節的學習要提高其響應規範維度的設計理念,掌握基本技能。