Spring @DeleteMapping
最后修改于 2023 年 10 月 18 日
Spring @DeleteMapping 教程展示了如何使用 @DeleteMapping 注解将 HTTP DELETE 请求映射到特定的处理器方法。我们创建一个经典的 Spring 应用程序。
Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。
@DeleteMapping
@DeleteMapping
注解将 HTTP DELETE 请求映射到特定的处理器方法。它是一个组合注解,作为 @RequestMapping(method = RequestMethod.DELETE)
的快捷方式。
Spring @DeleteMapping 示例
下面的应用程序使用 @DeleteMapping
来删除一个资源。我们使用注解来设置一个 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.IPostService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.Set; import static org.springframework.http.ResponseEntity.ok; @Controller public class MyController { @Autowired private IPostService postService; @GetMapping(value="/posts") public ResponseEntity<Set<Post>> all() { return ok().body(postService.all()); } @DeleteMapping(value = "/posts/{id}") public ResponseEntity<Long> deletePost(@PathVariable Long id) { var isRemoved = postService.delete(id); if (!isRemoved) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(id, HttpStatus.OK); } }
MyController
提供了请求路径和处理器方法之间的映射。我们有两个映射:一个用于 GET 请求,一个用于 DELETE 请求。
@GetMapping(value="/posts") public ResponseEntity<Set<Post>> all() { return ok().body(postService.all()); }
用 @GetMapping
注解的方法返回所有帖子。
@DeleteMapping(value = "/posts/{id}") public ResponseEntity<Long> deletePost(@PathVariable Long id) { var isRemoved = postService.delete(id); if (!isRemoved) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(id, HttpStatus.OK); }
deletePost
方法用 @DeleteMapping
注解。该方法的工作是尝试使用 IPostService
删除一个帖子。根据结果返回一个合适的 ResponseEntity
。
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 java.util.Set; public interface IPostService { boolean delete(Long id); Set<Post> all(); }
IPostService
包含两个契约方法:delete
和 all
。
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 implements IPostService { 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 boolean delete(Long id) { var isRemoved = this.posts.removeIf(post -> post.getId().equals(id)); return isRemoved; } public Set<Post> all() { return this.posts; } }
PostService
包含删除帖子和返回所有帖子的方法。我们不实现数据库层;相反,我们使用一个简单的内存集合。
注意: 在实际应用程序中,我们还会实现一个 Repository 层。
$ mvn jetty:run
我们运行 Jetty 服务器。
$ curl localhost:8080/posts [{"id":3,"content":"Post three"},{"id":4,"content":"Post four"}, {"id":1,"content":"Post one"},{"id":2,"content":"Post two"}]
使用 curl
工具,我们检索所有帖子。
$ curl -i -X DELETE localhost:8080/posts/1/ HTTP/1.1 200 OK Date: Wed, 21 Sep 2022 10:56:07 GMT Content-Type: application/json Transfer-Encoding: chunked Server: Jetty(9.4.49.v20220914) 1
我们使用 Id 1 删除一个帖子。
$ curl localhost:8080/posts [{"id":3,"content":"Post three"},{"id":4,"content":"Post four"}, {"id":2,"content":"Post two"}]
我们再次获取所有帖子;Id 为一的帖子已被删除。
在本文中,我们介绍了 @DeleteMapping
注解。
作者
列出 所有 Spring 教程。