gpt4 book ai didi

java - @RequestBody 不适用于 Rest 服务

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:45 26 4
gpt4 key购买 nike

我正在使用 AngularJS 和使用 Spring 的 WildFly 开发 Web 应用程序。

我的问题是我快疯了,因为注释 @requestBody 似乎工作不正常。

这是我的服务:

@ResponseBody
@RequestMapping(value = "/keyuser", method = RequestMethod.POST,
consumes = "application/json")
public KeyProfileUserSummary updateEmployee(@RequestBody KeyProfileUserSummary keyUser) {
return null;
}

这是我的对象 KeyProfileUserSummary 的成员:

private Integer id;
private String login;
private String password;
private String firstname;
private String lastname;
private UserRole userRole;

我不知道发生了什么,但我已经用其他类型的对象测试了这个服务,它工作得很好,但是在定义 KeyProfileUserSummary 时它不工作,我得到 ERROR 400 BAD REQUEST。我已经测试过将 @RequestBody 设置为“对象”,这样至少我可以看到即将发生的事情,并且从我的前端,我得到以下信息:

{id=3, login=aa, password=a, firstname=Martin, lastname=Müller, userRole=ROLE_USER} 

UserRole 是一个枚举。重要的是要明确 KeyProfileUserSummary 只是 KeyProfileUser 的摘要版本,但由于我在响应中获得的所有链接元素,我决定发送这个更轻的类。使用 KeyProfileUser 进行测试时效果很好,我在 Angular 端获得了 JSON 对象并可以将其发回。

在 Angular 方面,我没有对对象做任何事情。只需在列表中接收它,当按下编辑按钮时,只需将列表中的元素发回即可。这是我发送它的方式:

res = $http.post("url.../keyuser", user);

问题是,我的一切都与 KeyProfileUser 完美配合,但由于数据库可能变得非常庞大且引用资料很多,我决定切换到这个较轻的类,但现在我只得到这个 ERROR 400 BAD REQUEST ...我要上吊了:P

感谢您的帮助!

最佳答案

好吧,我终于找到了解决方案。

在我的 KeyProfileUserSummary 中,我只有一个采用 KeyProfileUser 并将属性设置为摘要版本的构造函数:

public KeyProfileUserSummary(KeyProfileUser keyProfileUser) {
this.id = keyProfileUser.getId();
this.login = keyProfileUser.getLogin();
this.password = keyProfileUser.getPassword();
this.firstname = keyProfileUser.getPerson().getFirstname();
this.lastname = keyProfileUser.getPerson().getLastname();
this.userRole = keyProfileUser.getUserRole();
}

显然,在调度程序 servlet 的第 993 行设置了一个断点(感谢@Clemens Eberwein 的提示)我意识到当从 JSON 对象解析时,Jackson 解析器需要一个空的构造函数!所以添加它解决了它并且完美地工作。

注意:对于 KeyProfileUser,它工作得很好,因为我们有用于 hibernate 的注释 @Entity,因此自动创建了空构造函数。

关于java - @RequestBody 不适用于 Rest 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35778628/

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