Java Spring MVC@RequestBody不使用jquery ajax?
这是我的ajax请求Java Spring MVC@RequestBody不使用jquery ajax?,java,jquery,json,ajax,spring-mvc,Java,Jquery,Json,Ajax,Spring Mvc,这是我的ajax请求 var dataModel = {name1:"value1", name2:"value2"}; $.ajax({ url: "/testURL", type: "POST", async: false, contentType: "application/json", data: dataModel,
var dataModel = {name1:"value1", name2:"value2"};
$.ajax({
url: "/testURL",
type: "POST",
async: false,
contentType: "application/json",
data: dataModel,
success: function(response) {
}
})
下面是我从SpringXML中获得的相关片段
<annotation-driven>
<!-- Message converters are added to use custom object mapper in MappingJackson2HttpMessageConverter.
StringHttpMessageConverter is required to avoid MappingJackson2HttpMessageConverter from converting a string into json.
-->
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter">
</beans:bean>
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper"/>
</beans:bean>
</message-converters>
</annotation-driven>
但我的请求甚至没有到达控制器。只要我删除@RequestBody CustomObject CustomObject
它就会工作。但是我想将json请求映射到
CustomObject具有@RequestBody
,但未发生不确定我在这里遗漏了什么?
事实上,当我检查request.getParameterMap()
时,它显示为空,但当我删除contentType:“application/json”
时,我看到参数映射被填充,但仍然是空的
然后得到下面的错误
`The server refused this request because the request entity is in a format not supported by the requested resource for the requested method`
这是我的CustomObject定义
public class CustomObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name1;
private String name2;
//getters and setters
}
已经通过了,但没有帮助
事实上,当我检查request.getParameterMap()时,它显示为空,但
一旦我删除contentType:“application/json”
没错。原因在于contentType:“application/json”
jquery在内部将数据转换为字符串。因此没有请求参数。如果没有contentType:“application/json”
,默认的contentType'是表单数据。因此,发送的数据将根据分隔符
&和
=`
另外,请尝试
data:JSON.stringify(dataModel)
,它应该可以工作我在列表中有数据,当我执行JSON.stringify(data)时,它将变为空白,editForm.credentials=[{attribute:'username',value:'t2'},{attribute:'password',value:'t2}]代码>同样在postman中工作。$.ajax({url:getContextPath()+“/abc/update”,类型:'POST',数据:dataTosend,contentType:'application/json',success:function(data){})代码>
public class CustomObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name1;
private String name2;
//getters and setters
}