How effective is Spring Boot's effective message?

2

I need to implement a successful message that is shown via json, for when my message is returning like this below;

Idonotknowhowtoimplementthismessage,Itrieditthatway;

@PostMappingpublicResponseEntity<Employee>criar(@Valid@RequestBodyEmployeeemployee,BindingResultresult,HttpServletResponseresponse,Modelmodel){model.addAttribute("mensagem", "Cadastro de Employee feita com sucesso");

    Employee employeeSalva = employeeRepository.save(employee);
    URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{codigo}")
            .buildAndExpand(employeeSalva.getId()).toUri();
        response.setHeader("Location", uri.toASCIIString());

        return ResponseEntity.created(uri).body(employeeSalva);


}

I tried to use the addAttribute method, but I did not succeed, could anyone please help me in the code so I can implement a successful message?

    
asked by anonymous 12.09.2018 / 12:58

1 answer

1

You need to return an object that represents the fields you want to return, in this case just a success message.

So you need to create a kind of Dto, fill it with the message and return it in ResponseEntity:

public class MensagemSucessoDto {
    private String mensagem;
    //criar construtor, get e set
}

Getting more or less like your code:

@PostMapping
public ResponseEntity<EmployeeDto> criar(@Valid @RequestBody Employee employee, BindingResult result,  HttpServletResponse response) {

    Employee employeeSalva = employeeRepository.save(employee);

    URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{codigo}")
            .buildAndExpand(employeeSalva.getId()).toUri();
        response.setHeader("Location", uri.toASCIIString());

        MensagemSucessoDto mensagemSucessoDto = new mensagemSucessoDto("Cadastro de Employee feita com sucesso");
        return ResponseEntity.created(uri).body(mensagemSucessoDto);
}

However, it would not be the best way to do this. It is common when creating a resource via POST, you return the values of the created resource (Employee) and tell whether it was successful or not via the HTTP code, which would be 201 CREATED . The code, following this pattern, would look like this:

  • Return a Dto that represents the fields you want to return: id , name , salary .
  • Save the Employee resource.
  • You create this Dto ( EmployeeDto ), fill Dto with Employee data, and return it in ResponseEntity , using the method you used ( ResponseEntity.created(uri).body(employeeDto) ) or new ResponseEntity<>(employeeDto, HttpStatus.CREATED) .
  • In addition, I do not recommend using the same Employee class in Request and Response, even more so if it is a hibernate entity (as I suspect is, in your case).

        
    12.09.2018 / 13:12