gpt4 book ai didi

java - 从 spring-boot Rest Controller 返回 JSON 对象

转载 作者:行者123 更新时间:2023-12-03 07:07:24 24 4
gpt4 key购买 nike

我正在尝试检查用户名在 spring-boot 中是否唯一。我想将结果作为 JSON 对象发送。这是 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
}
}

我想获得角度结果,以便我可以在组件中显示错误消息。我怎样才能做到这一点?

有角的一面

客户端.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()})});
}

在 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 ?
});

}

编辑

@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;
}

最佳答案

如果您使用的是 spring-boot-starter-web,您的项目已设置为返回 JSON。而不是 String 作为 checkEmailUnique 的返回值,使用您创建的对象类型。

这是一个例子:

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;
}

已编辑添加了更多示例。

关于java - 从 spring-boot Rest Controller 返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com