实现使用 POST 方法创建用户资源

在前面的步骤中,我们创建了简单的 RESTful 服务。在本节中,我们将使用 POST 方法将用户资源发布到特定的 URI "/users"。

在这里,我们将使用两个注解:@RequestBody@PostMapping

@RequestBody

@RequestBody 注解将 Web 请求的主体映射到方法参数上。请求的主体通过 HttpMessageConverter 传递给方法。它根据请求的内容类型解析方法参数。还可以通过在参数上使用 @Valid 注解来应用自动验证。

以下是一个例子,当我们在 createUser() 方法中使用 @RequestBody 注解时,它会映射到 user 参数。

@PostMapping

@PostMapping 注解是 @RequestMapping 注解的专用版本,它相当于 @RequestMapping(method = RequestMethod.POST) 的快捷方式。@PostMapping 方法处理与指定的 URI 匹配的 Http POST 请求。

现在我们要创建一个用户资源,并通过 POST 方法发布该资源。

步骤 1: 打开 UserResource.java 并添加 @PostMapping("/user")

步骤 2: 创建一个名为 createUser() 的方法,将 User 类的对象作为 Web 请求的主体。

步骤 3: 保存创建的用户。

UserResource.java

package cn.javatiku.server.main.user;  
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  
public class UserResource   
{  
@Autowired  
private UserDaoService service;  
@GetMapping("/users")  
public List<User> retriveAllUsers()  
{  
return service.findAll();  
}  
//retrieves a specific user detail  
@GetMapping("/users/{id}")  
public User retriveUser(@PathVariable int id)  
{  
return service.findOne(id);  
}  
//method that posts a new user detail   
@PostMapping("/users")  
public void createUser(@RequestBody User user)  
{  
User sevedUser=service.save(user);    
}  
}  

当我们刷新页面时,它返回 GET 请求。但是我们需要发送 POST 请求。我们可以通过 REST 客户端 发送 POST 请求。REST 客户端是设计用于从服务器使用服务(RESTful)的客户端。

接下来,我们来看看如何使用 REST 客户端。

步骤 4:https://www.getpostman.com/downloads/ 下载 Postman。

或者在浏览器中添加 Google Chrome 扩展:https://bit.ly/1HCOCwF

步骤 5: 启动 Postman 并进行注册。创建一个用户名。在这里,我们创建了用户名 javatiku 并点击 Submit 按钮。参考下面的图片:

restful-web-services-postman-for-chrome.png

步骤 6: 首先,我们检查 GET 请求。在地址栏中输入 URL http://localhost:8080/users/1,然后点击 Send 按钮。它将返回第一个用户的详细信息。

restful-web-services-postman-for-chrome2.png

步骤 7: 现在我们发送一个 POST 请求。

  • 将方法更改为 POST
  • 复制来自 "/users/1" 的响应主体。
  • 点击 Body 标签。现在我们为 POST 请求创建一个主体。
  • 选择 raw 选项。它将创建一个原始请求。
  • 粘贴复制的内容。
  • 删除 id,因为它会自动增加。
  • 将 "name" 更改为 "Thomas"。
  • 我们将数据以 JSON 格式发送,所以选择 JSON (application/json)
  • 输入 URL http://localhost:8080/users,然后点击 Send 按钮。
  • 点击窗口左侧的 Get 请求。
  • 现在我们将再次发送 Get 请求,所以将 URL 更改为 http://localhost:8080/users,然后点击 Send 按钮。它将显示所有用户,包括我们创建的用户。

restful-web-services-postman-for-chrome3.png

增强 POST 方法以返回正确的 HTTP 代码和状态位置

在本节中,我们将返回已创建资源的状态(Created)和资源的 URI("/users/6")。

ResponseEntity 类

ResponseEntity 是一个扩展了 HttpEntityHttpStatus 类的类。它定义在 org.springframework.http.ResponseEntity 中。

  • 它用于 RestTemplate@Controller 方法。
  • 它用作 getForEntity()exchange() 方法的参数。
  • 它还在 Spring MVC 中用作 @Controller 方法的参数。

RequestEntity 类的 created() 方法

created() 方法是 RequestEntity 类的静态方法。它创建一个具有 CREATED 状态的新构建器,并将位置标头设置为给定的 URI。

语法

public static ResponseEntity.BodyBuilder created(URI location)  

参数: 它接受一个 URI 位置作为参数。

返回值: 它返回已创建的构建器。

所有的 Http 状态码都是 Enum 常量,在 HttpStatus 类中定义。

ServletUriComponentsBuilder 类

ServletUriComponentsBuilder 是一个类,定义在 org.springframework.web.servlet.support.ServletUriComponentsBuilder 中。它扩展了 UriComponentsBuilder 类。它具有基于当前 HttpServletRequest 创建链接的额外静态工厂方法。

fromCurrentRequest() 方法

它与 fromRequest(HttpServletRequest) 方法类似,但是通过 RequestContextHolder 获取请求。

path() 方法

path()UriComponentsBuilder 类的方法。它将给定的路径附加到此构建器的现有路径上。给定的路径可以包含 URI 模板变量。

语法

public UriBuilderBuilder path(String path)  

参数: 它接受一个路径作为参数。

返回值: 它返回 UriComponentsBuilder

buildAndExpand() 方法

它构建 UriComponents 实例,并将 URI 模板变量替换为从数组中获取的值。这是一个快捷方法,它结合了对 build() 方法和 UriComponents.expand(Object... uriVariableValues) 方法的调用。

语法

public UriComponents buildAndExpand(Object...uriVariableValues)  

参数: 它接受 URI 变量值作为参数。

返回值: 它返回带有扩展值的 URI components

build() 方法

它从构建器中包含的各个组件构建 UriComponents 实例。

语法

public UriComponents build()  

参数: 它不接受任何参数。

返回值: 它返回 Uri Components

让我们看看如何返回已创建资源的状态,以及如何在响应中设置已创建资源的 URI。

步骤 1: 创建一个方法,该方法创建用户资源并返回 ResponseEntity

UserResource.java

package cn.javatiku.server.main.user;  
import java.net.URI;  
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;  
@RestController  
public class UserResource   
{  
@Autowired  
private UserDaoService service;  
@GetMapping("/users")  
public List<User> retriveAllUsers()  
{  
return service.findAll();  
}  
//retrieves a specific user detail  
@GetMapping("/users/{id}")  
public User retriveUser(@PathVariable int id)  
{  
return service.findOne(id);  
}  
//method that posts a new user detail and returns the status of HTTP and location of the user resource  
@PostMapping("/users")  
public ResponseEntity<Object> createUser(@RequestBody User user)  
{  
User sevedUser=service.save(user);    
URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();  
return ResponseEntity.created(location).build();  
}  
}  

步骤 2: 现在打开 REST 客户端 Postman 并创建一个 POST 请求。

步骤 3:History 标签下点击 POST 请求。

步骤 4: 点击 Body 标签,将用户名更改为 James

步骤 5: 确保选择了 JSON (application/json) 媒体类型。

步骤 5: 点击 Send 按钮。

在窗口的右侧,我们可以看到 Status: 201 Created。这意味着资源已经被正确创建。

步骤 6: 现在点击 Headers 标签以查看位置。位置是已创建资源的 URI。它显示了已创建用户 James 的位置,即 "/users/6"。

restful-web-services-postman-for-chrome4.png

如果客户端想要知道用户资源在哪里创建,只需从响应的头部获取位置。

标签: spring, Spring教程, Spring语言学习, Spring框架, Spring框架教程, Spring框架高级教程, spring boot, spring boot入门教程, spring boot学习教程, spring boot下载, spring boot框架入门, spring boot面试题, spring boot笔试题, spring boot技术,