java spring boot HTTP POST 请求不起作用

标签 java jquery ajax spring model-view-controller

对于我的应用程序,我正在编写一个 POST 请求以从复选框列表发送参数数组。它适用于 get 请求,但不适用于 post 请求。我的代码有什么错误。

我在客户端的代码,用于向服务器发送ajax请求。

$(".add").click(function(){

    monitoring.length=0;
    nonMonitoring.length=0;
    $('.modal-body input:checked').each(function() {
        monitoring.push($(this).val());
        });

    $('.addkeywords input:checked').each(function() {
        nonMonitoring.push($(this).val());
        });


//  alert(monitoring[2]+ " " + nonMonitoring[2]);
    var monitoringLength=monitoring.length;
    var nonMonitoringLength=nonMonitoring.length;

    $.ajax({
            type : "POST",
            url : '/rest/channelstats/my/rest/controller',
            data : {
            //  monitoring : monitoring,
            //  nonMonitoring: nonMonitoring,
                monitoringLength: monitoringLength,
                nonMonitoringLength: nonMonitoringLength,

            },
            success : function(data) {

            //  var keywordsList=data
                //console.log(keywordsList);
            //  htm = "" ;


            }


});


    })

我在服务器端的java代码。

@RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(@RequestParam(value="monitoringLength",required=true)int monitoringLength,@RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
    System.out.println("MonitoringLength =>" +monitoringLength);
    System.out.println("NonMonitoringLength=>" +nonMonitoringLength);

}

}

它适用于 HTTP GET 请求,但不适用于 POST 请求。我应该如何解决这个问题?

最佳答案

根据您的jquery post请求,您应该使用DAO (Data Access Object)解析请求数据。所以你应该添加类 Request

public class Request {

    private int monitoringLength;
    private int nonMonitoringLength;

    //getters and setters
} 

并将 Controller 更改为

@RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(@RequestBody Request request){
    System.out.println("MonitoringLength =>"+request.getMonitoringLength());            
    System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}

关于java spring boot HTTP POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367704/

相关文章:

javascript - 如何将ajax调用中的数组传递给 Controller ​​并使用Symfony 3返回它

javascript - 从浏览器外部调用 Javascript 函数?

javascript - 删除数据库中的上一行 单击按钮显示数据库中的下一行

java - 使用 Jackson 反序列化扩展 ArrayList 的 Java 对象

javascript - 在 Struts 1 中使用 AngularJS 进行 Ajax POST

Java:在创建父类(super class)类型的对象时使用子类的setter

javascript - 使用 Ajax 检查跨域 RSS 是否已更改

javascript - 使用 JQuery Mobile ui-datepicker 保存日期/事件

java - 如何检查Graph是否连接

java - 如何打破或退出Java中的方法?