How effective is the message of success in Spring Boot?

Asked

Viewed 717 times

2

I need to implement a success message that is shown via json, by when my message is returning this way below;

inserir a descrição da imagem aqui

I don’t know how to implement that message, I tried that way;

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

    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 method addAttribute, however I was unsuccessful, please ,could someone help me in the code so I can implement a message of success?

1 answer

1


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

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

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

Getting more or less like this 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 most Rest 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 the 201 CREATED. The code, following this pattern, would look like this:

  1. Return a Dto that represents the fields you want to return: id, name, salary.
  2. Saves the Employee resource.
  3. You create this Dto (EmployeeDto), fills Dto with Employee data and returns it to ResponseEntity, using the method you used (ResponseEntity.created(uri).body(employeeDto)) or new ResponseEntity<>(employeeDto, HttpStatus.CREATED).

Furthermore, I do not recommend using the same class Employee in Request and Response, especially if it is an entity of Hibernate (as I suspect it is, in your case).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.