我在使用ajax将json数据发送到控制器时遇到了问题

17 浏览
0 Comments

我在使用ajax将json数据发送到控制器时遇到了问题

我在使用ajax向控制器发送json数据时遇到了问题。

我认为我已经正确发送了数据,但是我收到了以下警告。

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'bno' is not present]

code:400

message:HTTP状态码400 – 错误请求h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}

HTTP状态码400 – 错误请求

Type 状态报告消息 找不到必需的整数参数 'bno'描述 由于被视为客户端错误的某些原因(例如,请求语法错误,无效的请求消息格式或欺骗性请求路由),服务器无法或不会处理请求。

Apache Tomcat/8.5.34

我将展示我的ajax代码

var headers = {"Content-Type" : "application/json"
        ,"X-HTTP-Method-Override" : "DELETE"
      };
$.ajax({
          url: root+"/restcmt/"+uid+"/"+cno
              , headers: headers
              , type: 'DELETE'
              , data : JSON.stringify({"bno":bno})
              , beforeSend : function(xhr){
                    xhr.setRequestHeader(_csrf_name, _csrf_token);
                }
              , success: function(result){
                  showcmtlist(bno);
              }
              , error: function(request,status,error){
                console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
                }
          });

以及我的控制器

    @RequestMapping(value="/{uid}/{cno}", method=RequestMethod.DELETE)
    public void deletecmt(@PathVariable int cno ,@PathVariable String uid,@RequestParam int bno
            ,@AuthenticationPrincipal SecurityCustomUser securityCustomUser) throws Exception{
    }

和请求载荷

{"bno":14}

我不确定出了什么问题。

出了什么问题?

0
0 Comments

问题出现的原因是在使用ajax发送json数据到控制器时遇到了问题。解决方法是参考Spring-World文档中的要求,确保请求的payload与控制器的参数类型相对应。这里的例子是使用一个POJO类作为参数类型。另外,为了解决ajax发送DELETE请求时将数据放在请求体中而不是放在查询字符串中的问题,可以参考https://github.com/jquery/jquery/issues/3269

0
0 Comments

问题原因:发送的json数据没有正确接收到Controller中。

解决方法:确保Controller方法中接收的参数类型与发送的json数据格式一致。

参考链接:https://stackoverflow.com/questions/28039709

感谢您的帮助,我现在知道了这两者之间的区别。谢谢!

0