【发布时间】:2014-06-27 08:38:37
【问题描述】:
这是我的控制器类 sn-p
@RequestMapping(value = "/createAgent", method = RequestMethod.POST)
@ResponseBody
public String createAgent(@RequestBody String json) {
System.out.println(json);
}
如何将 JSON 对象传递给此方法。我可以以任何方式通过 url 传递它吗?如果我这样通过(虽然这看起来很不对),
http://localhost:8080/SurveyApp3/createAgent/{"a_id": 8746574632, "pwd": "abcd", "pim_id": 3, "m_id":9738247882}
我收到一个错误提示
WARNING: No mapping found for HTTP request with URI [/SurveyApp3/createAgent/%7B%22a_id%22:%208746574632,%20%22pwd%22:%20%22abcd%22,%20%22pim_id%22:%203,%20%22m_id%22:9738247882%7D] in DispatcherServlet with name 'spring'
我还尝试使用欢迎文件 index.jsp 中的 ajax 请求
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
function sendAjax() {
$.ajax({
url: "/createAgent",
type: 'POST',
dataType: 'json',
data: "{\"a_id\":7645534265,\"pwd\":\"abcd\", \"pim_id\":3, \"m_id\":9738247882}",
contentType: 'application/json',
success: function(data) {
alert(data.a_id + " " + data.pwd);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
</body>
</html>
当我转到这个网址时,
http://localhost:8080/SurveyApp3/createAgent
我收到一条错误消息,指出不支持 GET 方法。我还是这个话题的新手,我无法弄清楚如何将 JSON 对象作为参数发送到 post 方法。 我哪里错了?
谢谢!
【问题讨论】:
-
当您在浏览器中访问 URL(如 localhost:8080/SurveyApp3/createAgent)时,默认方法是 GET。由于您的方法是 POST,服务器返回 405 Not Supported。
-
我如何将 JSON 值传递给方法呢?我不完全知道 (@RequestBody String json) 是什么以及如何获得它的价值。
-
运行 AJAX 调用时会发生什么?
-
我收到此错误警告:不支持请求方法“GET”
-
你试过 $.post 吗? api.jquery.com/jquery.post
标签: java json spring-mvc http-post