Spring MVC中的PUT请求 [英] PUT request in Spring MVC

查看:141
本文介绍了Spring MVC中的PUT请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Spring MVC中编写一个简单的 PUT 请求方法。我得到以下内容:

I'm trying to write a simple PUT request method in Spring MVC. I got the following:

@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'}

我也试过 @RequestBody 注释,但这也没有帮助。任何想法,我在这里做错了将不胜感激。

I also tried with @RequestBody annotation, but that also did not help. Any ideas what I'm doing wrong here would be greatly appreciated.

推荐答案

你没有告诉spring如何绑定名称和<来自请求的code>电子邮件参数。例如,通过添加 @RequestParam

You did not tell spring how to bind the name and email parameters from the request. For example, by adding a @RequestParam:

public @ResponseBody User updateUser(@PathVariable("id") long id, 
                                     @RequestParam String name, 
                                     @RequestParam String email) { ... }

name email 参数将从查询中填充请求中的字符串。例如,如果您向 /users/1?name=Josh&email=jb@ex.com 发出请求,您将收到以下回复:

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=jb@ex.com, you will get this response:

User{id=1, name='Josh', email='jb@ex.com'}

为了更多地了解定义处理程序方法,请查看spring 文档

In order to gain more insight about defining handler methods, check out the spring documentation.

这篇关于Spring MVC中的PUT请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆