【问题标题】:java spring rest parameter not workjava spring rest参数不起作用
【发布时间】: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">&times;</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">&times;</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


【解决方案1】:

在您的 Rest 代码中有一个 put 映射 @PutMapping("/notification/save/{id}"),但在您的 js 中由 post 方法 type: 'post', 调用,因此它返回 400 Bad Request,您应该使用 type: put,它等于您的 Rest 方法。

 @PutMapping("/notification/save/{id}")
 public @ResponseBody String update(@PathVariable("id") long id, 
 @RequestParam  AccountNotification accountNotification){
 .....
 }



  $.ajax({
     url: 'notification/save/'+id,
     params: params1,
     type: 'put',
     success:function(){
 }})

【讨论】:

  • {"timestamp":1511437558654,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message": “缺少所需的请求正文:public java.lang.String br.com.supportcomm.trust.web.NotificationController.update(long,br.com.supportcomm.trust.model.AccountNotification)”,“path”:“/next -trust/notification/save/4"}
  • 你能发布你的AccountNotification
  • 你不发送正文(JQuery 中的数据参数)
  • 您的实体类参数与您通过 ajax 请求发送的数据不匹配。
  • @Simon Martinelli 正确提到你应该使用@RequestParam 注释
【解决方案2】:

我解决了这个模式:

@RequestMapping(value={"/notification/save/{id}"},  method = {RequestMethod.GET, RequestMethod.POST},
         produces = "application/json"

        )
public @ResponseBody String update(@PathVariable("id") long id, AccountNotification accountNotification){
    String result="ok";

JavaScript:

 $("#saveChanges").on('click',function(){
		 var params1={
				 proxy:$(proxy).val() ,
				 port:$(port).val(),
				 uri:$(uri).val(),
				 actived:$(actived).is(':checked')
		 };
		 
         $.ajax({
             url: 'notification/save/'+id,
             data: params1,
             type: 'post',
             success:function(response) {

我用数据替换成js参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 2018-12-10
    • 2018-12-02
    • 1970-01-01
    • 2015-02-25
    • 2018-12-02
    • 2021-10-05
    • 2023-02-03
    相关资源
    最近更新 更多