springboot 統一json返回格式,並設置http響應碼


參考

  1. springboot 統一json返回格式

代碼

  1. 自定義響應類
@Data
public class ResponseBody<T> {
    public static final Integer SUCCESS = 0;
    public static final Integer ERROR = 1;
    protected Integer code      = 0;
    protected String  msg       = "";
    protected T  data;
    public ResponseBody(T data){
        this.setData(data);
    }
    public ResponseBody(Integer code){
        this.setCode(code);
    }
    public ResponseBody(Integer code, String msg){
        this.setCode(code);
        this.setMsg(msg);
    }

    public ResponseBody(T data, Integer code, String msg){
        this.setData(data);
        this.setCode(code);
        this.setMsg(msg);
    }
}
  1. 測試
@RestController
@RequestMapping("v1/test")
public class Test {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ResponseEntity<ResponseBody<Student>> index(){
        return ResponseEntity.ok( new ResponseBody( studentService.findById(1)));
    }
//    public ResponseBody<Student> index(){
//        return new ResponseBody( studentService.findById(1));
//    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM