我一直在努力将Jquery ajax发布数据作为@RequestBody发布到Spring控制器中。
我能够发送JSON字符串并捕获控制器中的JSON字符串。但是,无法将jQuery字符串从jquery ajax发送到控制器[无法转换为Object]。
以下是代码段:
# these are the variables we want to (ie are able to) extract from the movie object
metadata = ('title', 'rating', 'genre', "plot", "language", "runtime", "year", "color", "country" , "votes")
#creates dataframe with variable name headers
df = pd.DataFrame(np.random.randn(250, len(metadata)), columns=metadata)
#these are all different data types, including lists, this makes it compile
df = df.astype('object')
#populate df with movie objects
for i in range(250):
for j in metadata:
df.loc[i, j] = movies_list[i].get(j)
# convert to the right data types:
metadata_dict_dtypes = {"title": unicode,
"rating": float,
"genre":list,
"plot": str,
"language":list,
"runtime":list,
"year":int,
"color":list,
"country":list ,
"votes":int}
for colname, my_dtype in metadata_dict_dtypes.iteritems():
df[colname] = df[colname].astype(my_dtype)
// responseObject初始化:
**Ajax Call:**
function postLoad(){
$.ajax({
type : 'POST',
url : "ajaxhai.do",
contentType : "application/json",
cache : false,
data : responseObject, **//json-String**
dataType :"html",
success : function(data, textStatus) {
console.log("POST success");
$("#ajaxContent").html(data);
},
error : function(request, status, error) {
console.log("failed" + error);
}
});
}
我在pom中也有杰克逊依赖:
<c:if test='${not empty ajitems}'>
var responseObject = JSON.stringify('${ajitems}');
</c:if>
// ${ajitems}--> is the model attribute and setting it in javascript to //send it back to controller through ajax call
//Controller:
@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json") **//unable to convert to requestBody**
public String testAjaxPost(@RequestBody AjaxDto[] ajaxRes, Model model,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(ajaxRes);
return "ajaxform";
}
总是说:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.3</version>
</dependency>
但是当我按照以下方式更改控制器时,它就像魅力一样:
jquery-3.2.1.min.js:4 POST http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 400 (Bad Request)
我在这里失踪的是什么?我已经尝试了自动json转换的所有可能性仍然没有运气。
感谢任何帮助。
谢谢。
答案 0 :(得分:0)
当你期待控制器中的阵列时,请检查你想要发送的json。 json有问题。
同时检查您是否已注册MappingJackson2HttpMessageConverter
我认为您应该已经注册了。
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:autoDetectFields="false"
p:autoDetectGettersSetters="false"
p:failOnEmptyBeans="false"
p:indentOutput="true">
</bean>
</property>
</bean>
这是一个很好的例子。 Ajax请求
var requestObject = [{"product_Name":"One Product","descripction":"Essentials","category":null,"price":"100.00","mfg_Date":null,"image":null},
{"product_Name":"two Product","descripction":"Essentials 2","category":null,"price":"120.00","mfg_Date":null,"image":null}];
$.ajax({
type : 'POST',
url : "services/product",
cache : false,
contentType:"application/json;charset=utf-8",
data : JSON.stringify(requestObject),//json-String**
dataType :"application/json;charset=utf-8",
success : function(data, textStatus) {
console.log("POST success"+data);
/* $("#ajaxContent").html(data);*/
},
error : function(request, status, error) {
console.log("failed" + error);
}
});
这是接受此请求的控制器。
@RequestMapping(value = "/product",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public @ResponseBody
ResponseEntity<List<Product>> createProduct(@RequestBody Product[] products) {
return new ResponseEntity<List<Product>>(Arrays.asList(products), HttpStatus.OK);
}