How do I manipulate the http response using ModelAndView in java?

88 Views Asked by At

I want that when adding a data in the database, the status to be returned is 201 instead of 200. I tried to use the following code but it didn't work:

@PostMapping("/salvar")
public ModelAndView salvar(Artigo artigo) {
    ModelAndView mv = new ModelAndView(CADASTRA_ARTIGOS);
    artigoRepository.save(artigo);
    return mv;
}

I am also trying to avoid using ResponseEntity.

1

There are 1 best solutions below

0
On BEST ANSWER

The default return status code is 200. If you want different then you have to use ResponseEntity as shown below.

@PostMapping("/salvar")
public ModelAndView salvar(Artigo artigo) {
    Artigo artigoSaved = artigoRepository.save(artigo);
    return new ResponseEntity<>(artigoSaved, HttpStatus.CREATED);
}