Moot Kart
Moot Kart

Reputation: 11

Returning ResponseEntity with info

I'm kind of new with Spring. I have made following method:

public ResponseEntity<Borders> updateBorder(@Valid @RequestBody Borders borders) throws URISyntaxException {
    log.debug("REST request to update Borders : {}", borders);
    Boolean ok = deviceService.updateBorder(borders);
    return new ResponseEntity(ok ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST);
}

My method is now returning ResponseEntity with HttpStatus.CREATED or HttpStatus.BAD_REQUEST. When implementing frontEnd to my software I was wondering it would be very handy, if method could also return a String with HttpStatus. Like "Border is updated!" or "Border could not be updated because... pla pla".

What would be best way to return something more specific also to front-end?

Upvotes: 1

Views: 2517

Answers (2)

Javatar81
Javatar81

Reputation: 659

ResponseEntity allows to return three types of data:

  1. HTTP Status code
  2. Body
  3. HTTP Header

For each combination of this data you will find a matching constructor. What you are looking for is the body which is an arbitrary object containing the data to be returned. Depending on the Accept header of your request the body will be returned in the requested data format, e.g. application/json. You can even return a simple String as body:

public ResponseEntity<String> updateBorder(@Valid @RequestBody Borders borders) throws URISyntaxException {
    log.debug("REST request to update Borders : {}", borders);
    Boolean ok = deviceService.updateBorder(borders);
    return new ResponseEntity("Border could not be updated", ok ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST);
}

Upvotes: 0

kuhajeyan
kuhajeyan

Reputation: 11057

you can return something like this , but your method return type should be ResponseEntity < String >, and if you want you pass headers as well.

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

return new ResponseEntity("your message", ok ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST);

Upvotes: 1

Related Questions