I am trying to send a JSON object by AJAX to a Spring controller but receive an error 415:
我试图通过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."
“服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持。”
My Spring controller looks like this and is running on Tomcat 7 -
我的Spring控制器看起来像这样并且在Tomcat 7上运行 -
@RequestMapping(
value = "/ab/greeting",
method=RequestMethod.POST, headers = "Accept=*/*",
produces = "application/json")
public String greetingSubmit(@RequestBody Person p1) {
return "result";
}
The Person class is defined like this -
Person类定义如下 -
package ab;
public class Person {
String fname;
String lname;
}
Here is my javascript making the call -
这是我的javascript打电话 -
function getGreeting() {
$.ajax({
url : "/ab/greeting",
contentType: "application/json",
type: 'POST',
async: false,
data: JSON.stringify({ fname: "John", lname: "Doe" }),
success: function (data) {
}
});
}
Here are my dependencies Jackson related dependencies in my POM -
以下是我在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>
Ironically, it works when I try it on Spring Boot.
具有讽刺意味的是,当我在Spring Boot上尝试时,它可以工作。
On Tomcat, I have also tried using @ModelAttribute
in place of @RequestBody
- in which case, the request returns with a error code 200
but the p1 object comes out null in the controller.
在Tomcat上,我也尝试使用@ModelAttribute代替@RequestBody - 在这种情况下,请求返回错误代码200,但p1对象在控制器中出现null。
Is this related to the difference between Spring and Spring MVC? - apologies for the noob question. My controller class is annotated only with @Controller
.
这与Spring和Spring MVC之间的区别有关吗? - 为noob问题道歉。我的控制器类仅使用@Controller进行注释。
How do I modify this to be able to send a JSON object from AJAX to Spring POST controller? Eventually, I would like to send an array of 5 objects.
如何修改此能够将AJSON中的JSON对象发送到Spring POST控制器?最后,我想发送一个包含5个对象的数组。
Please help.
Thanks
1 个解决方案
#1
1
Add the consumes attribute
添加consumemes属性
@RequestMapping(value = "/ab/greeting", method=RequestMethod.POST,headers = "Accept=*/*",produces = "application/json", consumes="application/json")
public String greetingSubmit(@RequestBody Person p1) {
return "result";
}
#1
1
Add the consumes attribute
添加consumemes属性
@RequestMapping(value = "/ab/greeting", method=RequestMethod.POST,headers = "Accept=*/*",produces = "application/json", consumes="application/json")
public String greetingSubmit(@RequestBody Person p1) {
return "result";
}