1.Spring Boot接口请求简介
在Web开发中,构建RESTful服务是极其常见。Spring Boot通过简化配置和提供强大的注解支持,能够快速搭建并部署高效的API服务。在Spring Boot中,支持多种HTTP方法来处理不同的请求类型。这包括常见的GET、POST、PUT和DELETE,还包括OPTIONS、TRACE和HEAD等较少见但同样重要的方法。
-
GET 请求:用于从服务器检索信息。它不会对服务器上的资源进行任何修改。
URL 参数(Query Parameters):通过URL传递参数。
路径参数(Path Variables):通过URL路径传递参数 -
POST 请求:用于向服务器提交数据,通常会导致创建新资源
请求体(Request Body):通过请求体传递数据,通常用于创建资源。
表单数据(Form Data):通过表单提交数据 -
PUT 请求:用于更新现有资源或创建资源(如果资源不存在则创建)
通过请求体传递数据,通常用于更新现有资源。 -
DELETE 请求:用于删除资源。
通过URL路径传递参数,标识要删除的资源 -
OPTIONS 请求:用于查询目标资源所支持的通信选项。客户端可以通过发送OPTIONS请求来了解服务器支持哪些HTTP方法或其他通信选项
-
TRACE 请求:用于回显客户端发送的请求消息,主要用于诊断目的,以检查请求是否被中间服务器修改。
-
HEAD 请求:类似于GET请求,但只返回响应头信息而不包含实际内容,适用于仅需获取元数据的情况
类似于GET请求,但只返回响应头信息而不包含实际内容。
在Spring Boot中,创建一个接口很简单,通常定义一个能够处理HTTP请求的控制器(Controller)。这些控制器是通过使用@RestController注解来标识,并且可以处理来自客户端的各种类型的HTTP请求(如GET、POST等)。
2.Spring Boot接口示例
- 创建一个简单的Item类
class Item {
private Long id;
private String name;
public Item() {
}
public Item(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters and Setters
public Long getId() {
return id; }
public void setId(Long id) {
this.id = id; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
}
- 创建service类,处理Item的增删改查
@Service
public class ItemService {
private Map<Long, Item> itemStore = new HashMap<>();
public Item create(Item newItem) {
newItem.setId((long) (itemStore.size() + 1));
itemStore.put(newItem.getId(), newItem);
return newItem;
}
public Item update(Long id, Item updatedItem) {
if (itemStore.containsKey(id)) {
updatedItem.setId(id);
itemStore.put(id, updatedItem);
return updatedItem;
}
return null;
}
public void deleteById(Long id) {
itemStore.remove(id);
}
public boolean existsById(Long id) {
return itemStore.containsKey(id);
}
public Item findById(Long id) {
return itemStore.get(id);
}
}
- 创建Controller处理请求
@RestController
@RequestMapping("/api/items")
public class ItemController {
private final ItemService itemService = new ItemService();
// GET 请求
@GetMapping("/{id}")
public ResponseEntity<Item> getItem(@PathVariable Long id) {
Item item = itemService.findById(id);
if (item != null) {
return new ResponseEntity<>(item, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
// POST 请求
@PostMapping
public ResponseEntity<Item> createItem(@RequestBody Item newItem) {
Item createdItem = itemService.create(newItem);
return new ResponseEntity<>(createdItem, HttpStatus.CREATED);
}
// PUT 请求
@PutMapping("/{id}")
public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item updatedItem) {
Item item = itemService.update(id, updatedItem);
if (item != null) {
return new ResponseEntity<>(item, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
// DELETE 请求
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
if (itemService.existsById(id)) {
itemService.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
// OPTIONS 请求
@RequestMapping(method = RequestMethod.OPTIONS)
public ResponseEntity<?> options() {
Set<HttpMethod> allowedMethods = new HashSet<>();
allowedMethods.add(HttpMethod.GET);
allowedMethods.add(HttpMethod.POST);
allowedMethods.add(HttpMethod.PUT);
allowedMethods.add(HttpMethod.DELETE);
allowedMethods.add(HttpMethod.OPTIONS);
allowedMethods.add(HttpMethod.HEAD);
allowedMethods.add(HttpMethod.TRACE);
HttpHeaders headers = new HttpHeaders();
headers.setAllow(allowedMethods);
return new ResponseEntity<>(headers, HttpStatus.OK);
}
// TRACE 请求
@RequestMapping(method = RequestMethod.TRACE)
public ResponseEntity<String> trace(HttpServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return new ResponseEntity<>(sb.toString(), HttpStatus.OK);
}
// HEAD 请求
@RequestMapping(value