001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.web; 017 018import java.util.HashMap; 019import java.util.Map; 020import java.util.Objects; 021 022/** 023 * @author michael yang (fuhai999@gmail.com) 024 * @Date: 2020/4/6 025 */ 026public class ResponseEntity { 027 028 //响应的数据 029 private Object body; 030 031 //自定义响应头部信息 032 private Map<String, String> headers; 033 034 //默认http状态 035 private HttpStatus httpStatus = HttpStatus.OK; 036 037 038 public ResponseEntity() { 039 } 040 041 public ResponseEntity(Object body) { 042 this.body = body; 043 } 044 045 public ResponseEntity(Map<String, String> headers, HttpStatus httpStatus) { 046 this.headers = headers; 047 this.httpStatus = httpStatus; 048 } 049 050 public ResponseEntity(Object body, Map<String, String> headers, HttpStatus httpStatus) { 051 this.body = body; 052 this.headers = headers; 053 this.httpStatus = httpStatus; 054 } 055 056 public ResponseEntity body(Object body) { 057 this.body = body; 058 return this; 059 } 060 061 public ResponseEntity header(String key, String value) { 062 if (this.headers == null) { 063 this.headers = new HashMap<>(); 064 } 065 this.headers.put(key, value); 066 return this; 067 } 068 069 public ResponseEntity status(int status) { 070 for (HttpStatus httpStatus : HttpStatus.values()) { 071 if (Objects.equals(httpStatus.value(), status)) { 072 this.httpStatus = httpStatus; 073 break; 074 } 075 } 076 return this; 077 } 078 079 080 public ResponseEntity status(HttpStatus status) { 081 this.httpStatus = status; 082 return this; 083 } 084 085 086 public <T> T getBody() { 087 return (T) body; 088 } 089 090 public Map<String, String> getHeaders() { 091 return headers; 092 } 093 094 public HttpStatus getHttpStatus() { 095 return httpStatus; 096 } 097 098 099 public static ResponseEntity ok() { 100 ResponseEntity responseEntity = new ResponseEntity(); 101 return responseEntity.status(HttpStatus.OK); 102 } 103 104 105}