简体   繁体   中英

Spring @ResponseStatus returns empty response

In my Spring API I wanted to handle responses from operations like create, put and delete with Spring's annotation @ResponseStatus . Every endpoint works correctly but they always return empty response.

Why response from annotated endpoints is empty?

Controller:

import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping(value = "/v1/portfolios")
public class PortfolioController {

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@RequestBody Portfolio resource) {
        repo.save(resource);
    }   

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable("id") String id) {
        repo.removeById(id);
    }

}

Why response from annotated endpoints is empty?

Because your methods return void (means without body). Status code - it's not a body.

You can try this to return response with message explicity:

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> delete(@PathVariable("id") String id) {
   repo.removeById(id);
return new ResponseEntity<>("Your message here", HttpStatus.OK);
    }

Instead of ResponseEntity<String> you can put ResponseEntity<YourCustomObject> and then return new ResponseEntity<>(yourCustomObject instance, HttpStatus.OK); It will be conver into JSON during response.

You also can make this:

@ResponseStatus(value = HttpStatus.OK, reason = "Some reason")

and in this case you will return something like this:

{
    "timestamp": 1504007793776,
    "status": 200,
    "error": "OK",
    "message": "Some reason",
    "path": "/yourPath"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM