天天看點

使用spring ResponseEntity處理http響應

使用spring ResponseEntity處理http響應

簡介

使用spring時,達到同一目的通常有很多方法,對處理http響應也是一樣。本文我們學習如何通過ResponseEntity設定http相應内容、狀态以及頭資訊。

ResponseEntity

ResponseEntity辨別整個http相應:狀态碼、頭部資訊以及相應體内容。是以我們可以使用其對http響應實作完整配置。

如果需要使用ResponseEntity,必須在請求點傳回,通常在spring rest中實作。ResponseEntity是通用類型,是以可以使用任意類型作為響應體:

@GetMapping("/hello")

ResponseEntity<String> hello() {

    return new ResponseEntity<>("Hello World!", HttpStatus.OK);

}

1

2

3

4

可以通過程式設計方式指明響應狀态,是以根據不同場景傳回不同狀态:

@GetMapping("/age")

ResponseEntity<String> age(

  @RequestParam("yearOfBirth") int yearOfBirth) {

    if (isInFuture(yearOfBirth)) {

        return new ResponseEntity<>(

          "Year of birth cannot be in the future", 

          HttpStatus.BAD_REQUEST);

    }

    return new ResponseEntity<>(

      "Your age is " + calculateAge(yearOfBirth), 

      HttpStatus.OK);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

另外,還可以設定http響應頭:

@GetMapping("/customHeader")

ResponseEntity<String> customHeader() {

    HttpHeaders headers = new HttpHeaders();

    headers.add("Custom-Header", "foo");

    return new ResponseEntity<>(

      "Custom header set", headers, HttpStatus.OK);

}

1

2

3

4

5

6

7

8

而且, ResponseEntity提供了兩個内嵌的建構器接口: HeadersBuilder 和其子接口 BodyBuilder。是以我們能通過ResponseEntity的靜态方法直接通路。

最簡單的情況是相應包括一個主體及http 200響應碼:

@GetMapping("/hello")

ResponseEntity<String> hello() {

    return ResponseEntity.ok("Hello World!");

}

1

2

3

4

大多數常用的http 響應碼,可以通過下面static方法:

BodyBuilder accepted();

BodyBuilder badRequest();

BodyBuilder created(java.net.URI location);

HeadersBuilder<?> noContent();

HeadersBuilder<?> notFound();

BodyBuilder ok();

1

2

3

4

5

6

另外,可以能使用BodyBuilder status(HttpStatus status)和BodyBuilder status(int status) 方法設定http狀态。使用ResponseEntity BodyBuilder.body(T body)設定http響應體:

@GetMapping("/age")

ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {

    if (isInFuture(yearOfBirth)) {

        return ResponseEntity.badRequest()

            .body("Year of birth cannot be in the future");

    }

    return ResponseEntity.status(HttpStatus.OK)

        .body("Your age is " + calculateAge(yearOfBirth));

}

1

2

3

4

5

6

7

8

9

10

也可以自定義頭資訊:

@GetMapping("/customHeader")

ResponseEntity<String> customHeader() {

    return ResponseEntity.ok()

        .header("Custom-Header", "foo")

        .body("Custom header set");

}

1

2

3

4

5

6

因為BodyBuilder.body()傳回ResponseEntity 而不是 BodyBuilder,需要最後調用。注意使用HeaderBuilder 不能設定任何響應體屬性。

盡管ResponseEntity非常強大,但不應該過度使用。在一些簡單情況下,還有其他方法能滿足我們的需求,使代碼更整潔。

替代方法

@ResponseBody

典型spring mvc應用,請求點通常傳回html頁面。有時我們僅需要實際資料,如使用ajax請求。這時我們能通過@ResponseBody注解标記請求處理方法,審批人能夠處理方法結果值作為http響應體。

@ResponseStatus

當請求點成功傳回,spring提供http 200(ok)相應。如果請求點抛出異常,spring查找異常處理器,由其傳回相應的http狀态碼。對這些方法增加@ResponseStatus注解,spring會傳回自定義http狀态碼。

直接操作相應

Spring 也允許我們直接 javax.servlet.http.HttpServletResponse 對象;隻需要申明其作為方法參數: