常用的ResponseEntity.BodyBuilder和自定义ResponseEntity例子

ResponseEntity.ok() 和 ResponseEntity.BodyBuilder() 
返回200(HttpStatus.SC_OK)

@RequestMapping("/check")
public ResponseEntity check() {
    BodyBuilder builder = (BodyBuilder) ResponseEntity.ok();
    builder.allow(HttpMethod.GET);
    builder.contentType(MediaType.TEXT_HTML);
    builder.eTag("W/MyeTag\"");
    return builder.body("Hello World!");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

ResponseEntity.status() 
使用HttpStatus返回需要的HttpCode

@RequestMapping("/handle")
public ResponseEntity handle() {
   return ResponseEntity.status(HttpStatus.SC_CREATED).body("Created Success");
}
  • 1
  • 2
  • 3
  • 4

ResponseEntity.created() 
返回201(HttpStatus.SC_CREATED)

@RequestMapping("/handle")
public ResponseEntity handle() {
    URI location = null;
    try {
    location = new URI("http://www.concretepage.com/");
    } catch (URISyntaxException e) {
    e.printStackTrace();
    }
    return ResponseEntity.created(location).build();
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

ResponseEntity.accepted() 
返回202(HttpStatus.SC_ACCEPTED)

@RequestMapping("/handle")
public ResponseEntity handle() {
     return ResponseEntity.accepted().body("Hello World!");
} 
  • 1
  • 2
  • 3
  • 4

ResponseEntity.noContent() 
返回204(HttpStatus.SC_NO_CONTENT)

@RequestMapping("/handle")
public ResponseEntity handle() {
    return ResponseEntity.noContent().build();
} 
  • 1
  • 2
  • 3
  • 4

ResponseEntity.badRequest() 
返回400(HttpStatus.SC_BAD_REQUEST)

@RequestMapping("/handle")
public ResponseEntity handle() {
   return ResponseEntity.badRequest().body("Bad Request");
} 
  • 1
  • 2
  • 3
  • 4

ResponseEntity.notFound() 
返回404(HttpStatus.SC_NOT_FOUND)

@RequestMapping("/handle")
public ResponseEntity handle() {
    return ResponseEntity.notFound().build();
} 
  • 1
  • 2
  • 3
  • 4

你可能感兴趣的:(spring,mvc)