【发布时间】:2013-03-01 15:00:36
【问题描述】:
我试图找到如何在 Spring 中编写以从 REST 客户端发布 JSON。例如,我写道:
@RequestMapping(value = "/{userId}/add", method = RequestMethod.POST, headers = {"content-type=application/json"})
@ResponseBody
public Map<String, String> saveUser(@RequestBody User user, BindingResult result) {
Map<String, String> jsonResponse = new HashMap<String, String>();
if (result.hasErrors()) {
jsonResponse.put("Message", "Can't add the user");
jsonResponse.put("Code", "401");
return jsonResponse;
}
userService.addUser(user);
jsonResponse.put("Message", "Success add User");
jsonResponse.put("Code", "200");
return jsonResponse;
}
从 Firefox REST 客户端对其进行了最终测试。但我看到了 404 错误。我究竟做错了什么?感谢您的帮助。
【问题讨论】:
-
你发送给服务器的 HTTP 请求的内容是什么?
-
例如我试过这样 { "id": 7, "token": null, "nameUser": "Mulder Fox", "dateBirth": "25.10.1975", "role" :“ROLE_USER”,“职位”:“职位”,“电子邮件”:“fox@gmail.com”,“登录”:“muldfox”,“电话”:“+12356565”,“地址”:null,“组织": null, "兴趣": null }
-
有两种可能性:1) Spring 无法解析您的某个字段,2) JSON 对象中的字段与 User 对象中的字段不匹配,3) 您的 URL 可能是错的。如果您在问题中发布整个 HTTP 请求和您的 User 类,也许我们可以缩小范围。此外,如果您的日志中有异常堆栈跟踪,那也会很有帮助。
-
userId在您的RequestMapping路径中解析为什么? -
我检查了一个 URL 并且它是正确的,但是我有一个堆栈跟踪:org.springframework.web.servlet.PageNotFound - 没有为 servlet 请求找到匹配的处理程序方法:路径'/user/2/add ',方法'POST',参数map[[empty]]
标签: json spring rest jakarta-ee