有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jquery java spring引导HTTP POST请求不工作

对于我的应用程序,我正在编写一个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请求。我该如何解决这个问题


共 (1) 个答案

  1. # 1 楼答案

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

    public class Request {
    
        private int monitoringLength;
        private int nonMonitoringLength;
    
        //getters and setters
    } 
    

    并将控制器更改为

    @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());
    }