Java Spring MVC 中的 PUT 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35878351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PUT request in Spring MVC
提问by Maciej Szlosarczyk
I'm trying to write a simple PUT
request method in Spring MVC. I got the following:
我正在尝试PUT
在 Spring MVC 中编写一个简单的请求方法。我得到以下信息:
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public @ResponseBody User updateUser(@PathVariable("id") long id,
String name,
String email) {
User user = repository.findOne(id);
user.setName(name);
user.setEmail(email);
System.out.println(user.toString());
repository.save(user);
return user;
}
Which is obviously wrong, because it returns the following:
这显然是错误的,因为它返回以下内容:
User{id=1, name='null', email='null'}
I also tried with @RequestBody
annotation, but that also did not help. Any ideas what I'm doing wrong here would be greatly appreciated.
我也尝试使用@RequestBody
注释,但这也没有帮助。任何我在这里做错的想法将不胜感激。
采纳答案by Ali Dehghani
You did not tell spring how to bind the name
and email
parameters from the request. For example, by adding a @RequestParam
:
您没有告诉 spring 如何绑定请求中的name
和email
参数。例如,通过添加一个@RequestParam
:
public @ResponseBody User updateUser(@PathVariable("id") long id,
@RequestParam String name,
@RequestParam String email) { ... }
name
and email
parameters will be populated from the query strings in the request. For instance, if you fire a request to /users/1?name=Josh&[email protected]
, you will get this response:
name
和email
参数将从请求中的查询字符串填充。例如,如果您向 发出请求/users/1?name=Josh&[email protected]
,您将得到以下响应:
User{id=1, name='Josh', email='[email protected]'}
In order to gain more insight about defining handler methods, check out the spring documentation.
为了更深入地了解定义处理程序方法,请查看 spring文档。
回答by inafalcao
You can receive name
and email
whith the @RequestBody
annotation:
您可以接收name
和email
蒙山的@RequestBody
注释:
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public @ResponseBody User updateUser(@PathVariable("id") long id,
@RequestBody User user) {}
This is a better practice when it comes to REST applications, as your URL becomes more clean and rest-style.
You can even put a @Valid annotation on the User
and validate its properties.
当涉及到 REST 应用程序时,这是一种更好的做法,因为您的 URL 变得更加干净和休息风格。您甚至可以在 上放置 @Valid 注释User
并验证其属性。
On your postman client, you send the User
as a JSON, on the body of your request, not on the URL. Don't forget that your User
class should have the same fields of your sent JSON object.
在您的邮递员客户端上,您将User
JSON 作为 JSON发送到您的请求正文中,而不是发送到 URL 上。不要忘记您的User
类应该具有与您发送的 JSON 对象相同的字段。