弹簧 MVC 中不存在必需的字符串参数错误

2022-09-01 20:35:26

我尝试在Spring MVC中对我的控制器进行AJAX查询。

我的操作代码是:

@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestParam(value = "start_date") String start_date, @RequestParam(value = "end_date") String end_date, @RequestParam(value = "text") String text, @RequestParam(value = "userId") String userId){
    //some code    
}

我的Ajax查询是:

$.ajax({
        type: "POST",
        url:url,
        contentType: "application/json",
        data:     {
                start_date:   scheduler.getEvent(id).start_date,
                end_date:  scheduler.getEvent(id).end_date,
                text: scheduler.getEvent(id).text,
                userId: userId
        },
        success:function(result){
         //here some code
        }
    });

但是我得到了一个错误:

必需的字符串参数“start_date不存在

为什么?据我所知,我把它呈现得像(@RequestParam(value = "start_date") String start_date

UDP
现在我给404我的类来获取数据

public class EventData {
    public String end_date;
    public String start_date;
    public String text;
    public String userId;
    //Getters and setters
}

我的js AJAX调用是:

$.ajax({
    type: "POST",
    url:url,
    contentType: "application/json",
    // data: eventData,
    processData: false,
    data:    JSON.stringify({
        "start_date":   scheduler.getEventStartDate(id),
        "end_date":  scheduler.getEventEndDate(id),
        "text": scheduler.getEventText(id),
        "userId": "1"
    }),

控制器操作:

@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestBody EventData eventData){    
}

JSON 数据是:

end_date: "2013-10-03T20:05:00.000Z"
start_date: "2013-10-03T20:00:00.000Z"
text: "gfsgsdgs"
userId: "1"

答案 1

在服务器端,您希望请求参数作为查询字符串,但在客户端,您发送一个 json 对象。要绑定 json,您需要创建一个包含所有参数的单个类,并使用@RequestBody注释而不是@RequestParam。

@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestBody CommandBean commandBean){
    //some code
}

以下是更详细的说明。


答案 2

我有同样的问题。.我通过在post请求中指定配置参数来解决它:

var config = {
    transformRequest : angular.identity,
    headers: { "Content-Type": undefined }
}

$http.post('/getAllData', inputData, *config*).success(function(data,status) {
    $scope.loader.loading = false;
})

配置是我包含的参数,它开始工作。希望它能帮助:)


推荐