1. 程式人生 > >使用spring ResponseEntity來處理HTTP的返回請求

使用spring ResponseEntity來處理HTTP的返回請求

ota user cati row condition 簡單 參數 issue stat

通常情況下,在前後端分離的大背景下,我們後臺服務返回給前端的通常都是格式化的數據,比如Json,開始的時候,我們用json包生產一個json的字符串,配合http 協議的一些API 來自定義實現

            spring發展到現在,已經都包裝出來了通用的處理類:ResponseEntity ,此類繼承自HttpEntity
 public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;

/**
 * Create a new {@code ResponseEntity} with the given status code, and no body nor headers.
 * @param status the status code
 */
public ResponseEntity(HttpStatus status) {
    this(null, null, status);
}

/**
 * Create a new {@code ResponseEntity} with the given body and status code, and no headers.
 * @param body the entity body
 * @param status the status code
 */
public ResponseEntity(@Nullable T body, HttpStatus status) {
    this(body, null, status);
}
            並且做了擴展,用來處理http請求過程中的狀態碼 ,header,body 等數據。

ResponseEntity是一種泛型類型。因此,我們可以使用任何類型作為響應主體:

@Controller
public class XXXController{br/>@GetMapping("/hello")
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}

這裏字符串"Hello World!"作為字符串返回給REST端。

我們可以設置HTTP標頭:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");

return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}

設置自定義標頭:

@GetMapping("/customHeader")

ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")

如果將一個對象放入:

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK);
}

返回是JSON字符串:

[ { ‘name’: ‘jdon‘}]

下面是返回對象的JSON列表:

public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}

以上是通過ResponseEntity這個對象在代碼中靈活操控響應,但是在一般情況下我們只是想返回一個帶有數據的正常響應,那麽只要使用@註解即可

@ResponseBody
在類級別使用@Controller標註情況下, @ResponseBody註解告訴返回的對象將自動序列化為JSON,並通過回控制器的HttpResponse對象。

@Controller
public class XXXController{

@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}

將返回客戶端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

在@RestController註解了類的情況下,我們就不需要再使用@ResponseBody了,可以直接返回對象,並使用ResponseStatus返回狀態碼!

@ResponseStatus
ResponseStatus雖然只是規定了返回的狀態,但是只需要標註在方法上,簡單,而且狀態碼與返回類型分離,比較清晰。我們將上面返回對象列表的代碼使用ResponseStatus改寫如下,註意類級別@RestController:

@RestController
public class XXXController{

@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}

這也會返回客戶端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

這樣的代碼更加專註於業務。

直接操控響應
Spring還允許我們直接訪問javax.servlet.http.HttpServletResponse對象; 我們只需要將它聲明為方法參數:

@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}

由於Spring在底層實現之上提供了抽象和附加功能,因此如果以這種方式直接操縱響應,會失去很多Spring提供方便功能。

實例代碼:

import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.constraints.*;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-03-09T21:32:18.308+08:00")

@Api(value = "tag", tags={ "tag", }, description = "the tag API")
public interface TagApi {

@ApiOperation(value = "獲取問題概要標簽列表", notes = "get_issue_summary_tags", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tags",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "項目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

@ApiOperation(value = "獲取問題概要標簽值列表", notes = "get_tag_values", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tag_value/{tag_type}",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getTagValues(@NotNull @ApiParam(value = "項目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey, @ApiParam(value = "標簽類型 app: 應用 device: 設備 server_name:服務名稱 level:級別 logger:日誌 os: 系統 user: 用戶 url:URL transaction:事物", required = true) @PathVariable("tag_type") String tagType, @NotNull @Min(1) @ApiParam(value = "當前頁數", required = true, defaultValue = "1") @RequestParam(value = "page_number", required = true, defaultValue = "1") Integer pageNumber, @NotNull @Min(1) @ApiParam(value = "每頁顯示條數", required = true, defaultValue = "10") @RequestParam(value = "page_size", required = true, defaultValue = "10") Integer pageSize) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

}

@Controller
public class TagApiController implements TagApi {

private final static Logger logger = LoggerFactory.getLogger(TagApiController.class);

@Autowired
private TagService tagService;

@Override
public ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "項目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    OperateResult operateResult = new OperateResult();
    try {
        Preconditions.checkArgument(StringUtils.isNotBlank(projectKey));
        Preconditions.checkArgument(StringUtils.isNotBlank(issueSummaryKey));
        List<TagDetail> tagValueArrayList = tagService.getIssueSummaryTagList(projectKey, issueSummaryKey);
        operateResult = OperateResult.success(tagValueArrayList);
        return new ResponseEntity<OperateResult>(operateResult,HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getIssueSummaryTags error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR,e);
        return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

使用spring ResponseEntity來處理HTTP的返回請求