Spring @DeleteMapping 教程展示了如何使用@DeleteMapping 注解将 HTTP DELETE 请求映射到特定的处理程序方法。
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
这是项目结构。
pom.xml
<?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>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring-version>5.1.3.RELEASE</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>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.14.v20181114</version>
</plugin>
</plugins>
</build>
</project>
在pom.xml
文件中,我们具有项目依赖项。
resources/logback.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 日志库的配置文件。
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.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
。
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/IPostService.java
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()
。
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 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
具有删除帖子并返回所有帖子的方法。 我们没有实现数据库层。 相反,我们使用一个简单的内存集合。
注意:在实际应用中,我们还将实现存储库层。
$ 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, 01 May 2019 12:59:07 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Server: Jetty(9.4.14.v20181114)
1
我们删除 ID 为 1 的信息。
$ curl localhost:8080/posts
[{"id":3,"content":"Post three"},{"id":4,"content":"Post four"},{"id":2,"content":"Post two"}]
我们又收到了所有帖子。 编号为 1 的帖子已删除。
在本教程中,我们介绍了@DeleteMapping
注解。