我已经阅读了许多类似的问题,包括:JQuery,Spring MVC @RequestBody和JSON - 使它 与JQuery/Ajax和Spring 一起使用JSON请求
要求是服务器只接受application/json类型.我正在使用Spring MVC控制器.代码通过@ResponseBody以JSON形式发送响应.我想通过Spring MVC Controller中的@RequestBody获取信息.我正在使用JSP将JSON发送到Spring MVC Controller.我的代码和Spring MVC如下所示:
我是JSON和Javascript的新手.
JSP - index.jsp
<%@page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
var frm = $("#myForm");
var dat = JSON.stringify(frm.serializeArray());
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: dat,
contentType: 'application/json',
dataType: 'json',
error: function() {
alert('failure');
}
success: function(hxr) {
alert("Success: " + xhr);
}
});
);
};
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/save" method="POST" accept="application/json" onclick="i()">
<input type="text" …Run Code Online (Sandbox Code Playgroud) 我在这个POST请求上收到400个错误请求.知道这里的问题是什么吗?日志在这里.
调节器
@Controller
public class AjaxController {
@RequestMapping(value="/addKeys", method=RequestMethod.POST, consumes="application/json; charset=UTF-8")
public ResponseEntity<String> addKeys(@RequestParam(value="keys") ArrayList<Keys> keys){
System.out.println("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"+keys);
}
}
Run Code Online (Sandbox Code Playgroud)
上下文servlet.xml中
<beans>
<mvc:annotation-driven />
<context:component-scan base-package="com.canon.fw.controller" />
<bean id="defaultViews" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</beans>
Run Code Online (Sandbox Code Playgroud)
阿贾克斯
tmpList = '[{"key":"camera","label":"Camera"},{"key":"mobile","label":"Mobile"}]';
$.ajax({
type: 'POST',
url: ctx+'/ajx/addKeys',
data: JSON.stringify({"keys": tmpList }),
success: function(r){
if(r.model.status=='success'){
debugger;
//glist.push(elem.key);
//addToList(elem.key, elem.label);
highlightInfoDisc();
}
},
dataType: 'json',
contentType: 'application/json'
});
Run Code Online (Sandbox Code Playgroud)
FireBug - URL
http://localhost:8080/Di/ajx/addKeys
Run Code Online (Sandbox Code Playgroud)
Firebug - 响应标题
Cache-Control must-revalidate,no-cache,no-store
Content-Length 1384
Content-Type text/html; charset=iso-8859-1
Server Jetty(6.1.26)
Run Code Online (Sandbox Code Playgroud)
Firebug - 请求标题 …