【发布时间】:2017-11-23 11:36:15
【问题描述】:
我创建了将数据传递给 spring rest 但无法正常工作的代码,请参阅下面的代码:
@PutMapping("/notification/save/{id}")
public @ResponseBody String update(@PathVariable("id") long id, @RequestBody AccountNotification accountNotification){
String result="ok";
ServiceAccount serviceAccount = new ServiceAccount();
serviceAccount.setId(id);
//accountNotification.setServiceAccount( serviceAccount );
//result =notificationsService.update(id,accountNotification);
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
JSONObject accountNotificationJSON = new JSONObject();
if(result.equals("ok")) {
accountNotificationJSON.put("success", "true");
accountNotificationJSON.put("messages", "Successfully Saved");
}
else {
accountNotificationJSON.put("success", "false");
accountNotificationJSON.put("messages", "NOT Successfully Saved");
}
jArray.put(accountNotificationJSON);
jObject.put("data", jArray);
} catch (JSONException jse) {
logger.error( jse.getMessage());
}
return jObject.toString();
}
我的 javascrit 有:
$("#saveChanges").on('click',function(){
var params1={
proxy:$(proxy).val() ,
port:$(port).val(),
uri:$(uri).val(),
actived:$(actived).val()=="on"?true:false
};
$.ajax({
url: 'notification/save/'+id,
params: params1,
type: 'post',
success:function(response) {
if(response.data[0].success == "true") {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.data[0].messages+
'</div>');
// close the modal
$("#editMember").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.data[0].messages+
'</div>');
}
},
error: function(x, e) {
alert(x);
}
});
在这种情况下,ajax 代码返回 400。有人知道为什么吗?感谢如果撤销 @RequestBody 注释,其余部分已被调用,但参数 accountNotifications 已初始化但未传递 valeus。
【问题讨论】:
-
把
PutMapping改成RequestMapping -
不工作,我在这种模式之前尝试过:@RequestMapping(value={"/notification/save/{id}"},produces = "application/json", method= {RequestMethod. POST})
标签: java spring rest spring-mvc parameter-passing