Mr.*_*guy 7 java rest spring json put
因此,在我修复了"415 media media not supported"错误(不支持415媒体)后,我遇到了一个新问题.我RequestBody总是空着的.当我通过Chrome PostMan发送请求时,我总是得到一个只有空值的序列化实体.我使用Spring (4.2.3.RELEASE),Jackson-databind (2.6.3)并jackson-core (2.6.3)在我的项目.我在我的项目中使用基于注释的配置(@EnableWebMvc以使spring自动发现 HTTPMessageConverters).
其他帖子
我知道stackoverflow上的其他帖子,几乎相同的问题.但他们没有给我答案.此外,大多数帖子都是针对较旧的Spring版本(4.0之前版本),所以现在有些东西完全不同了.
类似帖子:
Spring的@RequestBody在POST上提供空字符串
弹簧控制器
在我的春天,@RestController我有以下代码:
@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT)
public UserLocation updateUserLocation(@PathVariable("id") int id, UserLocation user) {
return user;
}
Run Code Online (Sandbox Code Playgroud)
我使用单独的模型类(UserLocation)进行数据绑定.这是因为这样我可以更好地控制我的API发送和接收的数据.
数据绑定类(UserLocation)
UserLocation类包含3个属性,包含构造函数和所需的getter和setter.(我可以公开这些属性,但我首先要解决这个问题).
public class UserLocation {
private Float latitude;
private Float longitude;
private Date lastActive;
}
Run Code Online (Sandbox Code Playgroud)
JSON正文
通过我的AngularJS Ajax调用($http.PUT)我使用以下数据调用spring控制器:
{
"latitude": 52.899370,
"longitude": 5.804548,
"lastActive": 1449052628407
}
Run Code Online (Sandbox Code Playgroud)
PostMan请求
我正在开发一个Cordova应用程序,所以为了测试请求而不需要将我的应用程序构建到我的手机上,我使用的是Chrome PostMan插件.
我正在拨打以下电话:
URL: http://server:port/app/location/update/1
Method: PUT
Headers: Content-Type: application/json
Body:
{
"latitude": 52.899370,
"longitude": 5.804548,
"timestamp": 1449052628407
}
Run Code Online (Sandbox Code Playgroud)
请求结果
根据请求,我得到以下结果:
{"latitude":null,"longitude":null,"lastActive":null}
Run Code Online (Sandbox Code Playgroud)
这意味着Spring确实创建了我的UserLocation类的新实例,但它没有用正文中的数据填充它.
Spring PUT方法
在Spring控制器中使用PUT方法时,是不是立即更新了实体?那么这意味着控制器中没有额外的逻辑来更新实体吗?(如果实体当然是Hibernate/JPA模型,可以更新).
我似乎无法弄清楚问题.谁知道我做错了什么?
更新
添加@RequestBody到我的控制器代码:
@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT)
public UserLocation updateUserLocation(@PathVariable("id") int id, @RequestBody UserLocation user) {
return user;
}
Run Code Online (Sandbox Code Playgroud)
让我回到原来的问题(415媒体不支持).添加此操作会抛出415 Media不支持的错误,我似乎无法修复.
固定.解决方法如下
我没有在Controller中看到UserLocation对象的@RequestBody?还要确保您的属性具有getter和setter.
public UserLocation updateUserLocation(@PathVariable("id") int id, UserLocation user) {
Run Code Online (Sandbox Code Playgroud)
在执行HTTP PUT时,您必须添加额外的逻辑来将对象持久保存到数据库中.您需要调用DAO或Repository来保留对象.通常,您将传入的UserLocation对象映射到您持久存在的真实JPA/Hibernate实体.这不会自动发生.
问题是您错过了使用注释UserLocation参数 @RequestBody
..updateUserLocation(@PathVariable("id") int id, @RequestBody UserLocation user)
Run Code Online (Sandbox Code Playgroud)
还要确保为memeber变量生成getters和.settersUserLocation
| 归档时间: |
|
| 查看次数: |
13635 次 |
| 最近记录: |