Sign up for Spring Boot

Asked

Viewed 428 times

0

Good afternoon, you guys. I’m having difficulties to implement my Register on Spring Boot. I’m willing to do the method in three ways(if,else if,else) that if it is all right to register, that if anyone already exists with that email then from "Existing" and any error is "Invalid". But it is not working, the method I did to see if there is already in the bank the Person I am registering this correct? Someone can help me as I post and if the code is right or if there is some way to improve. Thank you.


Repository.

String findByEmail(String email)

------
Controller.

@PostMapping  
public ResponseEntity<Pessoa> cadastrar(@RequestBody Pessoa p) {  
        if(p.getEmail() == repository.findByEmail(p.getEmail())){    
            return ResponseEntity.status(400).build();  
        }else if(p != null) {  
            return ResponseEntity.ok().body(repository.save(p));
        }else {  
            return ResponseEntity.badRequest().build();  
        }    
    }
  • When you say it’s not working you need to be clearer, what’s not working ? the validation ? some error is being spit out ? what the behaviour of the request is ?

  • I see you didn’t call anything to register

  • @Isaíasdelimacoelho when I register an email with one that already exists in the table database Pessoa it adds the same way and I do not want it, and I wanted to know how to add some message like "Successfully registered" "Existing" "Invalid "

  • @nullptr arranged !

  • @Isaíasdelimacoelho I am using the Postman to make the requisitions, I wanted that in the Response came this message you know? And do you have any tips to improve this code? I’m finding it very pig.

1 answer

1

Hi,

I would not put this logic of existing or new registration in the same service (Rest) I think the controller should have a method to register new (POST) and a method to update an existing (PUT), even to take advantage of semantics (meaning of HTTP methods, PUT = update, POST = insert, DELETE = remove, etc)

Would something like this

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> cadastrar(@RequestBody Pessoa p) {
    try {
        Pessoa novaPessoa = service.save(p);
        return ResponseEntity.created(new URI("/pessoas/" + novaPessoa.getId())).build();
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Ocorreu um erro ao tentar salvar uma essoa", e);
    }
}

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> atualizar(@RequestBody Pessoa p, @PathVariable("id") Integer id) {
    try {
        p.setId(id);
        service.save(p);
        return ResponseEntity.noContent().build();
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus..BAD_REQUEST,
                "Ocorreu um erro ao tentar atualizar os dados da pessoa de id " + id, e);
    }
}   

And to test your API

POST /pessoas - adiciona uma pessoa
PUT /pessoas/{1} - atualiza os dados da pessoa de id 1
  • If you set the id the repository will already know that you are updating the data of an existing entity

  • In my example I passed the id to update, but Voce can pass something else like email, and at the time of searching the id Voce uses email

  • Uoooooou, thank you André !! I have seen many people using Responseentity<? > but I could never understand why, could you summarize me? About . noContent what is?

  • Responseentity is a spring web class that basically "encapsulates" a response and passes a return status (which must follow the conventions of http methods), noContent for example returns a status 204

  • https://pt.wikipedia.org/wiki/Lista_de_c%C3%B3digos_de_estado_http#204_Nenhum_conte%C3%Bado! 204 No content The server has successfully processed the request, but no response is required.

  • To make it cleaner, you could keep the @PostMapping and @PutMapping

Show 1 more comment

Browser other questions tagged

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