【发布时间】:2015-12-03 13:18:45
【问题描述】:
我的 Spring Rest 控制器有问题。
我正在尝试将(PUT)数据从我的客户端(angularJS)发布到我的服务器(Spring),但每次我尝试发送我收到 415 Media not supported 错误。
使用 Maven,我已将 jackson-core (2.6.3) 和 jackson-databind (2.6.3) 添加到我的 Spring API 中。我还使用@EnableWebMvc 将Jackson 消息转换器自动添加到Spring。在我的 Spring 控制器中,我使用 @RestController 来访问 Spring 的 REST 方法。
我的 REST API 控制器:
@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public RippleUser updateUserLocation(@PathVariable("id") Integer id, @RequestBody RippleUser user) {
return user;
}
我尝试过不同类型的消费:
MediaType.APPLICATION_JSON_VALUE"application/json"- 不消耗
- 等等
我的 RippleUser 模型 (部分)
@Entity
@Table(name = "user")
@JsonRootName(value = "user")
public class RippleUser implements Serializable {
@NotNull
@Column(name = "active", nullable = false)
private boolean activeUser;
@Column(name = "latitude", nullable = true)
private Float lattitude;
@Column(name = "longitude", nullable = true)
private Float longitude;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "lastActive", nullable = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private Date timestamp;
}
在这个模型中,我拥有所有必要的 getter 和 setter。
我的 AngularJS 客户端:
httpService.updateInBackend = function (url, data, callback, errorCallback) {
http.put(url, data)
.then(function successCallback(response) {
callback(response.data);
}, function errorCallback(response) {
errorCallback(response);
});
};
网址: http://server:port/app/location/update/{id}
数据:
params: {
{
"user": {
"latitude": 52.899370,
"longitude": 5.804548,
"timestamp": 1449052628407
}
}
};
对于这种方法,我还将@JsonRootName(value = "user") 添加到我的 RippleUser 模型中。
我也尝试过不使用用户属性(也将其从我的模型中删除):
params: {
{
"latitude": 52.899370,
"longitude": 5.804548,
"timestamp": 1449052628407
}
};
AngularJS HTTP 方法(PUT、POST、DELETE、GET 等)检查参数中的类型并自动设置正确的标头。
Chrome 邮递员
只是为了确保我也在 Chrome Postman 插件
中尝试过这种方法网址: http://server:port/app/location/update/2
方法:PUT
标题: Content-Type: application/json
正文:
{
"latitude": 52.899370,
"longitude": 5.804548,
"timestamp": 1449052628407
}
这给出的错误是:
HTTP Status 415 The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
更新
当我将@ResponseBody 从 RippleUser 更改为 String 时,我可以在 RestController 中接收信息:
@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public RippleUser updateUserLocation(@PathVariable("id") Integer id, @RequestBody String user) {
return user;
}
我也尝试发送一个空的用户对象,但这会导致相同的错误消息
我的问题的答案如下。
【问题讨论】:
-
所以你的方法的类型是
RippleUser,而你返回的是String? -
@Jason Z,这只是为了测试我是否可以通过该方法。我得到了一个 Json 字符串,所以该方法有效。该代码仅用于测试目的
标签: java angularjs json spring spring-restcontroller