Home  >  Spring 4

Spring 4 MVC ResponseEntity.BodyBuilder and ResponseEntity Enhancements Example

By Arvind Rai, April 11, 2015
ResponseEntity generates response with a given status code and its body. In Spring 4, ResponseEntity.BodyBuilder has been introduced that defines body of response entity. BodyBuilder has three methods as body(), contentLength() and contentType(). In ResponseEntity some new methods has been added like ok(), created(), accepted() etc. That returns the instance of ResponseEntity.BodyBuilder with the respective status code.

ResponseEntity.ok() and ResponseEntity.BodyBuilder

Sets 200 status.
@RequestMapping("/check")
public ResponseEntity<String> check() {
	BodyBuilder builder = (BodyBuilder) ResponseEntity.ok();
	builder.allow(HttpMethod.GET);
	builder.contentType(MediaType.TEXT_HTML);
	builder.eTag("W/MyeTag\"");
	return builder.body("Hello World!");
}

ResponseEntity.status()

Sets the required status using HttpStatus .
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
   return ResponseEntity.status(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED).body("BANDWIDTH LIMIT EXCEEDED");
}

ResponseEntity.created()

Sets 201 status.
@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
    URI location = null;
    try {
	location = new URI("http://www.concretepage.com/");
    } catch (URISyntaxException e) {
	e.printStackTrace();
    }
    return ResponseEntity.created(location).build();
} 

ResponseEntity.accepted()

Sets 202 status.
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
     return ResponseEntity.accepted().body("Hello World!");
} 

ResponseEntity.noContent()

Sets 204 status.
@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
    return ResponseEntity.noContent().build();
} 

ResponseEntity.badRequest()

Sets 400 bad request sttaus.
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
   return ResponseEntity.badRequest().body("Bad Request");
} 

ResponseEntity.notFound()

Sets 404 not found status.
@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
	return ResponseEntity.notFound().build();
} 

ResponseEntity.unprocessableEntity()

Sets 422 Unprocessable Entity status.
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
	return ResponseEntity.unprocessableEntity().body("Cannot process");
} 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus







Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us