Spring @PostMapping 教程显示了如何使用@PostMapping 注解将 HTTP POST 请求映射到特定的处理程序方法。
Spring 是用于创建企业应用的流行 Java 应用框架。
@PostMapping
@PostMapping注释将 HTTP POST 请求映射到特定的处理程序方法。 它是一个组合的注释,用作@RequestMapping(method = RequestMethod.POST)的快捷方式。
Spring @PostMapping示例
以下应用使用@PostMapping创建新资源。 在此示例中,我们使用注解来设置 Spring Web 应用。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ ├───config
│ │ │ MyWebInitializer.java
│ │ │ WebConfig.java
│ │ ├───controller
│ │ │ MyController.java
│ │ ├───model
│ │ │ Post.java
│ │ └───service
│ │ PostService.java
│ └───resources
│ logback.xml
└───test
└───java
这是项目结构。
pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
在pom.xml文件中,我们具有项目依赖项。
resources/logback.xml
logback.xml是 Logback 日志库的配置文件。
com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return null;
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
MyWebInitializer注册 Spring DispatcherServlet,它是 Spring Web 应用的前端控制器。
@Override
protected Class>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
getServletConfigClasses()返回 Web 配置类。
com/zetcode/config/WebConfig.java
package com.zetcode.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig {
}
WebConfig通过@EnableWebMvc启用 Spring MVC 注解,并为com.zetcode软件包配置组件扫描。
com/zetcode/controller/MyController.java
package com.zetcode.controller;
import com.zetcode.model.Post;
import com.zetcode.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import static org.springframework.http.ResponseEntity.ok;
@Controller
public class MyController {
@Autowired
private PostService postService;
@GetMapping(value="/posts")
public ResponseEntity
return ok().body(postService.all());
}
@PostMapping(value = "/posts")
public ResponseEntity
UriComponentsBuilder uriComponentsBuilder) {
var content = request.getParameter("content");
var post = new Post();
post.setContent(content);
post = postService.save(post);
UriComponents uriComponents =
uriComponentsBuilder.path("/posts/{id}").buildAndExpand(post.getId());
var location = uriComponents.toUri();
return ResponseEntity.created(location).build();
}
}
MyController提供请求路径和处理程序方法之间的映射。
注:这是一个很好的做法,在响应头返回新创建资源的位置。
@PostMapping(value = "/posts")
public ResponseEntity
UriComponentsBuilder uriComponentsBuilder) {
@PostMapping将createPost()方法映射到/posts URL。
var content = request.getParameter("content");
我们获得 POST 请求的content参数。
var post = new Post();
post.setContent(content);
post = postService.save(post);
创建一个新帖子,并将其保存在一个帖子服务中。
UriComponents uriComponents =
uriComponentsBuilder.path("/posts/{id}").buildAndExpand(post.getId());
var location = uriComponents.toUri();
使用UriComponentsBuilder构建位置 URI。
return ResponseEntity.created(location).build();
返回带有位置 URI 的响应实体。
com/zetcode/model/Post.java
package com.zetcode.model;
import java.util.Objects;
public class Post {
private Long id;
private String content;
public Post() {
}
public Post(Long id, String content) {
this.id = id;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equals(id, post.id) &&
Objects.equals(content, post.content);
}
@Override
public int hashCode() {
return Objects.hash(id, content);
}
}
这是一个简单的Post bean。 它具有两个属性:id和content。
com/zetcode/service/PostService.java
package com.zetcode.service;
import com.zetcode.model.Post;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
@Service
public class PostService {
private final AtomicLong counter = new AtomicLong();
private final Set
new Post(counter.incrementAndGet(), "Post two"), new Post(counter.incrementAndGet(), "Post three"),
new Post(counter.incrementAndGet(), "Post four")));
public Post save(Post p) {
var post = new Post(counter.incrementAndGet(), p.getContent());
this.posts.add(post);
return post;
}
public Set
return this.posts;
}
}
PostService具有保存帖子并返回所有帖子的方法。 我们没有实现数据库层。 相反,我们使用一个简单的内存集合。
$ mvn jetty:run
我们运行 Jetty 服务器。
$ curl -i -d "content=Post five" -X POST http://localhost:8080/posts
HTTP/1.1 201 Created
Date: Tue, 30 Apr 2019 09:49:10 GMT
Location: http://localhost:8080/posts/5
Content-Length: 0
Server: Jetty(9.4.14.v20181114)
创建一个新帖子。 注意位置标头。
$ curl localhost:8080/posts
[{"id":3,"content":"Post three"},{"id":4,"content":"Post four"},
{"id":1,"content":"Post one"},{"id":5,"content":"Post five"},{"id":2,"content":"Post two"}]
我们得到所有帖子。
在本教程中,我们介绍了@PostMapping注解。