将JSON对象发送到Spring POST控制器

时间:2016-11-13 21:48:13

标签: json ajax spring spring-mvc

我正在尝试通过 AJAX JSON 对象发送到Spring控制器,但收到错误415:

"The server refused this request because the request entity is in a format not supported by the requested resource for the requested method."

我的Spring控制器看起来像这样,并且在Tomcat 7上运行 -

@RequestMapping(
    value = "/ab/greeting", 
    method=RequestMethod.POST, headers = "Accept=*/*",
    produces = "application/json")
public String greetingSubmit(@RequestBody Person p1) {
    return "result";
}

Person类定义如下 -

package ab;

public class Person {

    String fname;
    String lname;
} 

这是我的javascript打电话 -

function getGreeting() {
        $.ajax({
            url : "/ab/greeting",
            contentType: "application/json",
            type: 'POST',
            async: false,
            data: JSON.stringify({ fname: "John", lname: "Doe" }),
            success: function (data) {
            }
        });
    }

以下是我在POM中与杰克逊相关的依赖关系 -

<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
        </dependency>

具有讽刺意味的是,当我在Spring Boot上尝试它时,它会起作用。

在Tomcat上,我也尝试使用@ModelAttribute代替@RequestBody - 在这种情况下,请求返回error code 200但p1对象在控制器中出现null。

这与Spring和Spring MVC之间的区别有关吗? - 为noob问题道歉。我的控制器类仅使用@Controller进行注释。

如何修改此能够将AJSON中的JSON对象发送到Spring POST控制器?最后,我想发送一个包含5个对象的数组。

请帮忙。

由于

2 个答案:

答案 0 :(得分:1)

添加消费属性

@RequestMapping(value = "/ab/greeting", method=RequestMethod.POST,headers = "Accept=*/*",produces = "application/json", consumes="application/json")
public String greetingSubmit(@RequestBody Person p1) {
    return "result";
}

答案 1 :(得分:0)

将数据从您的视图写入js控制台,并检查数据是否为空

相关问题