简体   繁体   English

从spring-boot rest控制器返回JSON对象

[英]Return JSON object from a spring-boot rest Controller

I'm trying to check if the username is unique in spring-boot. 我正在尝试检查用户名在spring-boot中是否唯一。 I want to send the result as JSON object. 我想将结果作为JSON对象发送。 This is the REST controller 这是REST控制器

@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 在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. 如果您使用的是spring-boot-starter-web,则您的项目已设置为返回JSON。 Instead of String as the return value from checkEmailUnique , use an object type that you create. 使用您创建的对象类型代替String作为checkEmailUnique的返回值。

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. Rest方法的返回类型为String。您可以使用用户定义的对象代替任何String,该对象在其中放置了布尔变量(例如status),可以在其中发送用户名是否存在。 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 您也可以使用ResponseEntity作为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. 根据响应类型,您可以直接确定电子邮件是否退出,而不是在这种情况下返回json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 spring-boot 返回 JSON 响应作为 CSV 文件 controller - Return a JSON response as CSV file from spring-boot controller 单元测试 Spring-boot Rest Controller - Unit Test Spring-boot Rest Controller How to pass JSON Object and return Object from Spring rest controller - How to pass JSON Object and return Object from Spring rest controller Spring Boot Rest Controller:返回默认的Error JSON - Spring Boot Rest Controller: Return default Error JSON Payara 5上的Spring-Boot Rest Controller会忽略JAXB批注 - Spring-Boot Rest Controller on Payara 5 ignores JAXB annotations 在Spring Boot Rest Controller中解析Json数组init单个对象 - Parse Json array init single object in Spring boot Rest Controller 在 java/spring-boot 中,如果找不到项目,返回空 json 对象的最干净的方法是什么 - In java/spring-boot what is the cleanest way to return an empty json object if an item is not found 无法从 Spring-Boot 控制器呈现 thymleaf 页面。 只打印输出中的返回字符串 - Unable to render thymleaf page from Spring-Boot controller. Prints only the return string in output 如何在spring-boot数据休息时在POST json中传递@EmbeddedId - How to pass @EmbeddedId in POST json in spring-boot data rest 控制器中的身份验证对象错误 [Spring-Boot] - Wrong Authentication-Object in Controller [Spring-Boot]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM