简体   繁体   中英

Return JSON object from a spring-boot rest Controller

I'm trying to check if the username is unique in spring-boot. I want to send the result as JSON object. This is the REST controller

@RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
public String checkEmailUnique(@RequestBody String username){

    AppUser app = userRepo.findByUsername(username);
    if(app!=null){
        // I want to return somthing like emailNotTaken: true
    }
    else{
        // and here : emailNotTaken: false  
    }
}

I want to get the result in angular so I can show an error message in my component. How can I do that?

Angular side

client.Service.Ts

checkEmailNotTaken(email:string){
    if(this.authService.getToken()==null) {
      this.authService.loadToken();
    }
    return this.http.post(this.host+
      "/checkEmailUnique/",{email},{headers:new HttpHeaders({'Authorization':this.authService.getToken()})});
  }

in client.component.ts

ngOnInit() {

    this.form = this.formBuilder.group({
      prenom: ['', Validators.required],
      nom: ['', Validators.required],
      tel: ['', Validators.required],
      cin: ['', Validators.required],
      username: ['', Validators.required , Validators.email  , this.validateEmailNotTaken.bind(this)],
      passwordG: this.formBuilder.group({
        password: ['',[Validators.required,Validators.minLength(9)]],
        Confirmationpassword : ['',[Validators.required,Validators.minLength(9)]]

      }, {validator: passwordMatch})

    });
  }

    validateEmailNotTaken(control: AbstractControl) {
        return this.clientService.checkEmailNotTaken(control.value).map(res => {
          return  // what to do here ?
        });

      }

EDIT

@RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
    public EmailStatusCheckJson checkEmailUnique(@RequestBody final String username){

        final EmailStatusCheckJson returnValue = new EmailStatusCheckJson();


         AppUser app = userRepo.findByUsername(username);


         if(app!=null){
             returnValue.setEmailIsAvailable(false);
         }
         else{
             returnValue.setEmailIsAvailable(true);

         }

         return returnValue;
    }

If you are using the spring-boot-starter-web, your project is already set to return JSON. Instead of String as the return value from checkEmailUnique , use an object type that you create.

Here is an example:

public class EmailStatusCheckJson
{
    private Boolean emailIsAvailable;

    public Boolean getEmailIsAvailable()
    {
        return emailIsAvailable;
    }

    public void setEmailIsAvailable(
        final Boolean newValue)
    {
        emailIsAvailable = newValue
    }
}


@RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
public EmailStatusCheckJson checkEmailUnique(@RequestBody final String username)
{
    final EmailStatusCheckJson returnValue = new EmailStatusCheckJson();

    if (...) // email is available.
    {
        returnValue.setEmailIsAvailable(true);
    }
    else
    {
        returnValue.setEmailIsAvailable(false);
    }

    return returnValue;        
}

Edited added more example.

Rest method have a return type as String .In place of any String you can use a user defined object where(inside there) put a boolean variable eg status there you can send whether the username is present or not. According to the response from the rest side you can forward towards angular.

You could also do this way using ResponseEntity as the return value to your RestController

public ResponseEntity<?> checkEmailUnique(@RequestBody String username){
    AppUser app = userRepo.findByUsername(username);
    if(null != app) {
        return ResponseEntity.badRequest().build(); // Will return a 400 response
    }
    return ResponseEntity.ok().build(); // Will return a 200 response
}

Base on the response type you could directly identify if the email exits or not instead of returning json in this case.

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