gpt4 book ai didi

java - 当对象通过 post 命令发送到 spring WebApp 时,对象字段为 null

转载 作者:行者123 更新时间:2023-12-02 11:03:43 25 4
gpt4 key购买 nike

我制作了一种方法,将发布请求发送到我的 Spring Web 应用程序以创建新用户。发送的对象有 3 个字段,即用户名、电子邮件地址和密码。

我已经验证了这些值在对象发送到服务器时就存在。下面是我的代码:

我的 UserService 中的方法:

  createUser(newUser: UserCreateDTO): Observable<Response> {
return this.http.post<Response>(this.authUrl + "/user/create", newUser);
}

我尝试将 Response 更改为 anyUserCreateDTO,但结果始终相同。对象已到达,但字段均为空。

我的用户组件中的方法:

  createUser():void{
this.loading = true;
this.userService.createUser(new UserCreateDTO(this.userForm.get('userName').value,
this.userForm.get('emailAddress').value,
this.userForm.get('password').value))
.subscribe((response: Response) => {
if(response.ok)
this.msgs.push({severity:'success', summary:'Success', detail: response.statusText});
else
this.msgs.push({severity:'error', summary:'Error', detail: response.statusText});
this.loading = false;
});
}

正在发送的对象:

export class UserCreateDTO {
userName: string;
emailAddress: string;
password: string;

constructor(userName?: string, emailAddress?: string, password?: string){
this.userName = userName;
this.emailAddress = emailAddress;
this.password = password;
}
}

这是在服务器端接收对象的端点:

@PostMapping("/create")
private ResponseEntity<String> createNewUser(UserCreateDTO newUser) {
Status status = userService.createUser(newUser);
return ResponseEntity.status(status.isSuccess() ?
HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(status.getInfo());
}

谁能给我一些建议吗?问题出在我的 Angular 代码中还是我的 Spring 代码中?谢谢。

编辑:

下面是请求负载:

{userName: "1", emailAddress: "1", password: "1"}
emailAddress
:
"1"
password
:
"1"
userName
:
"1"

所以是的,我认为它正在发送。但由于空字段引起的空指针异常,我收到了 500 响应。

最佳答案

在你的 Controller 中,你需要告诉方法从哪里获取newUser。在本例中,它来自 POST 正文,因此添加 @RequestBody 注释,如下所示:

@PostMapping("/create")
private ResponseEntity<String> createNewUser(@RequestBody UserCreateDTO newUser) {
Status status = userService.createUser(newUser);
return ResponseEntity.status(status.isSuccess() ?
HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(status.getInfo());
}

关于java - 当对象通过 post 命令发送到 spring WebApp 时,对象字段为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51141887/

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