Spring MVC中不存在必需的String参数错误 [英] Required String parameter is not present error in Spring MVC

查看:652
本文介绍了Spring MVC中不存在必需的String参数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Spring MVC中向我的控制器发出一个AJAX查询。

I try to make an AJAX query to my controller in Spring MVC.

我的操作代码是:

@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不存在

Required String parameter ''start_date is not present

为什么?
我知道我把它呈现为(@ RequestParam(value =start_date)String start_date

UDP

现在我给404
我的班级拿数据

UDP
Now I give 404 My class to take data

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

我的js AJAX电话是:

My js AJAX call is:

$.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"


推荐答案

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

On the server side you expect your request parameters as query strings but on client side you send a json object. To bind a json you will need to create a single class holding all your parameters and use the @RequestBody annotation instead of @RequestParam.

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

这是一个更详细的解释。

Here is a more detailed explanation.

这篇关于Spring MVC中不存在必需的String参数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆