原文: http://zetcode.com/spring/postmapping/

Spring @PostMapping教程显示了如何使用@PostMapping注解将 HTTP POST 请求映射到特定的处理器方法。

Spring 是用于创建企业应用的流行 Java 应用框架。

@PostMapping

@PostMapping注解将 HTTP POST 请求映射到特定的处理器方法。 它是一个组合的注解,用作@RequestMapping(method = RequestMethod.POST)的快捷方式。

Spring @PostMapping示例

以下应用使用@PostMapping创建新资源。 在此示例中,我们使用注解来设置 Spring Web 应用。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. ├───config
  8. MyWebInitializer.java
  9. WebConfig.java
  10. ├───controller
  11. MyController.java
  12. ├───model
  13. Post.java
  14. └───service
  15. PostService.java
  16. └───resources
  17. logback.xml
  18. └───test
  19. └───java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>postmappingex</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. <spring-version>5.1.3.RELEASE</spring-version>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>javax.servlet</groupId>
  20. <artifactId>javax.servlet-api</artifactId>
  21. <version>4.0.1</version>
  22. <scope>provided</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-webmvc</artifactId>
  27. <version>5.1.3.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>com.fasterxml.jackson.core</groupId>
  31. <artifactId>jackson-databind</artifactId>
  32. <version>2.9.8</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.apache.maven.plugins</groupId>
  39. <artifactId>maven-war-plugin</artifactId>
  40. <version>3.2.2</version>
  41. </plugin>
  42. <plugin>
  43. <groupId>org.eclipse.jetty</groupId>
  44. <artifactId>jetty-maven-plugin</artifactId>
  45. <version>9.4.14.v20181114</version>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>

pom.xml文件中,我们具有项目依赖项。

resources/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <logger name="org.springframework" level="ERROR"/>
  4. <logger name="com.zetcode" level="INFO"/>
  5. <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
  6. <encoder>
  7. <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
  8. </Pattern>
  9. </encoder>
  10. </appender>
  11. <root>
  12. <level value="INFO" />
  13. <appender-ref ref="consoleAppender" />
  14. </root>
  15. </configuration>

logback.xml是 Logback 日志库的配置文件。

com/zetcode/config/MyWebInitializer.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  4. @Configuration
  5. public class MyWebInitializer extends
  6. AbstractAnnotationConfigDispatcherServletInitializer {
  7. @Override
  8. protected Class<?>[] getRootConfigClasses() {
  9. return null;
  10. }
  11. @Override
  12. protected Class<?>[] getServletConfigClasses() {
  13. return new Class[]{WebConfig.class};
  14. }
  15. @Override
  16. protected String[] getServletMappings() {
  17. return new String[]{"/"};
  18. }
  19. }

MyWebInitializer注册 Spring DispatcherServlet,它是 Spring Web 应用的前端控制器。

  1. @Override
  2. protected Class<?>[] getServletConfigClasses() {
  3. return new Class[]{WebConfig.class};
  4. }

getServletConfigClasses()返回 Web 配置类。

com/zetcode/config/WebConfig.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  5. @Configuration
  6. @EnableWebMvc
  7. @ComponentScan(basePackages = {"com.zetcode"})
  8. public class WebConfig {
  9. }

WebConfig通过@EnableWebMvc启用 Spring MVC 注解,并为com.zetcode包配置组件扫描。

com/zetcode/controller/MyController.java

  1. package com.zetcode.controller;
  2. import com.zetcode.model.Post;
  3. import com.zetcode.service.PostService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.util.UriComponents;
  10. import org.springframework.web.util.UriComponentsBuilder;
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.util.Set;
  13. import static org.springframework.http.ResponseEntity.ok;
  14. @Controller
  15. public class MyController {
  16. @Autowired
  17. private PostService postService;
  18. @GetMapping(value="/posts")
  19. public ResponseEntity<Set<Post>> all() {
  20. return ok().body(postService.all());
  21. }
  22. @PostMapping(value = "/posts")
  23. public ResponseEntity<Post> createPost(HttpServletRequest request,
  24. UriComponentsBuilder uriComponentsBuilder) {
  25. var content = request.getParameter("content");
  26. var post = new Post();
  27. post.setContent(content);
  28. post = postService.save(post);
  29. UriComponents uriComponents =
  30. uriComponentsBuilder.path("/posts/{id}").buildAndExpand(post.getId());
  31. var location = uriComponents.toUri();
  32. return ResponseEntity.created(location).build();
  33. }
  34. }

MyController提供请求路径和处理器方法之间的映射。

注意:这是一个很好的做法,在响应头返回新创建资源的位置。

  1. @PostMapping(value = "/posts")
  2. public ResponseEntity<Post> createPost(HttpServletRequest request,
  3. UriComponentsBuilder uriComponentsBuilder) {

@PostMappingcreatePost()方法映射到/posts URL。

  1. var content = request.getParameter("content");

我们获得 POST 请求的content参数。

  1. var post = new Post();
  2. post.setContent(content);
  3. post = postService.save(post);

创建一个新帖子,并将其保存在一个帖子服务中。

  1. UriComponents uriComponents =
  2. uriComponentsBuilder.path("/posts/{id}").buildAndExpand(post.getId());
  3. var location = uriComponents.toUri();

使用UriComponentsBuilder构建位置 URI。

  1. return ResponseEntity.created(location).build();

返回带有位置 URI 的响应实体。

com/zetcode/model/Post.java

  1. package com.zetcode.model;
  2. import java.util.Objects;
  3. public class Post {
  4. private Long id;
  5. private String content;
  6. public Post() {
  7. }
  8. public Post(Long id, String content) {
  9. this.id = id;
  10. this.content = content;
  11. }
  12. public Long getId() {
  13. return id;
  14. }
  15. public void setId(Long id) {
  16. this.id = id;
  17. }
  18. public String getContent() {
  19. return content;
  20. }
  21. public void setContent(String content) {
  22. this.content = content;
  23. }
  24. @Override
  25. public boolean equals(Object o) {
  26. if (this == o) return true;
  27. if (o == null || getClass() != o.getClass()) return false;
  28. Post post = (Post) o;
  29. return Objects.equals(id, post.id) &&
  30. Objects.equals(content, post.content);
  31. }
  32. @Override
  33. public int hashCode() {
  34. return Objects.hash(id, content);
  35. }
  36. }

这是一个简单的Post bean。 它具有两个属性:idcontent

com/zetcode/service/PostService.java

  1. package com.zetcode.service;
  2. import com.zetcode.model.Post;
  3. import org.springframework.stereotype.Service;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6. import java.util.concurrent.atomic.AtomicLong;
  7. @Service
  8. public class PostService {
  9. private final AtomicLong counter = new AtomicLong();
  10. private final Set<Post> posts = new HashSet<>(Set.of(new Post(counter.incrementAndGet(), "Post one"),
  11. new Post(counter.incrementAndGet(), "Post two"), new Post(counter.incrementAndGet(), "Post three"),
  12. new Post(counter.incrementAndGet(), "Post four")));
  13. public Post save(Post p) {
  14. var post = new Post(counter.incrementAndGet(), p.getContent());
  15. this.posts.add(post);
  16. return post;
  17. }
  18. public Set<Post> all() {
  19. return this.posts;
  20. }
  21. }

PostService具有保存帖子并返回所有帖子的方法。 我们没有实现数据库层。 相反,我们使用一个简单的内存集合。

  1. $ mvn jetty:run

我们运行 Jetty 服务器。

  1. $ curl -i -d "content=Post five" -X POST http://localhost:8080/posts
  2. HTTP/1.1 201 Created
  3. Date: Tue, 30 Apr 2019 09:49:10 GMT
  4. Location: http://localhost:8080/posts/5
  5. Content-Length: 0
  6. Server: Jetty(9.4.14.v20181114)

创建一个新帖子。 注意位置标头。

  1. $ curl localhost:8080/posts
  2. [{"id":3,"content":"Post three"},{"id":4,"content":"Post four"},
  3. {"id":1,"content":"Post one"},{"id":5,"content":"Post five"},{"id":2,"content":"Post two"}]

我们得到所有帖子。

在本教程中,我们介绍了@PostMapping注解。

您可能也对这些相关教程感兴趣: Spring @GetMapping教程Spring @RequestMapping教程Spring @MatrixVariable教程Java 教程,或列出所有 Spring 教程