Spring @PostMapping
最后修改于 2023 年 10 月 18 日
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
这是项目结构。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>postmappingex</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.49.v20220914</version>
</plugin>
</plugins>
</build>
</project>
在 pom.xml 文件中,我们有项目依赖项。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.springframework" level="ERROR"/>
<logger name="com.zetcode" level="INFO"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
logback.xml 是 Logback 日志库的配置文件。
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 配置类。
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 包配置组件扫描。
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<Set<Post>> all() {
return ok().body(postService.all());
}
@PostMapping(value = "/posts")
public ResponseEntity<Post> createPost(HttpServletRequest request,
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<Post> createPost(HttpServletRequest request,
UriComponentsBuilder uriComponentsBuilder) {
@PostMapping 将 createPost 方法映射到 /posts URL。
var content = request.getParameter("content");
我们获取 POST 请求的 content 参数。
var post = new Post(); post.setContent(content); post = postService.save(post);
使用 post 服务创建并保存一个新帖子。
UriComponents uriComponents =
uriComponentsBuilder.path("/posts/{id}").buildAndExpand(post.getId());
var location = uriComponents.toUri();
使用 UriComponentsBuilder 构建位置 URI。
return ResponseEntity.created(location).build();
返回一个带有位置 URI 的响应实体。
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。
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<Post> posts = new HashSet<>(Set.of(new Post(counter.incrementAndGet(), "Post one"),
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<Post> all() {
return this.posts;
}
}
PostService 具有保存帖子和返回所有帖子的方法。我们不实现数据库层;而是使用简单的内存集合。
$ mvn jetty:run
我们运行 Jetty 服务器。
$ curl -i -d "content=Post five" -X POST https://:8080/posts HTTP/1.1 201 Created Date: Thu, 22 Sep 2022 09:10:11 GMT Location: https://:8080/posts/5 Content-Length: 0 Server: Jetty(9.4.49.v20220914)
创建一个新帖子。请注意 location 头。
$ 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 注解。
作者
列出 所有 Spring 教程。