spring - 请求映射到列表中的特定项目
问题描述
抱歉,我是 Spring Boot 新手并正在尝试学习,我有这段代码,当我运行它时,如果我输入任何 url ,它将打开我的目录项的 json 请求localhost/catalog/(any userid)
。但我想将其缩小到 1 个特定的用户 ID,我该怎么做?例如,如果我输入 l,ocalhost/catalog/friends
我将只获得朋友的信息,如果我输入,localhost/catalog/gameofthrones
我将只获得关于 gameofthrones 的信息,而不是整个列表
代码:
package com.poc.moviecatalog.controller;
import com.poc.moviecatalog.models.CatalogItem;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/catalog")
public class MovieController {
@RequestMapping("/{userId}")
public List<CatalogItem> getCatalog(@PathVariable("userId") String userId) {
return Arrays.asList(
new CatalogItem("friends", "test", 9),
new CatalogItem("gameofthrones", "test2", 3)
);
}
}
解决方案
你可以尝试这样的事情:
@RestController
@RequestMapping("/catalog")
public class MovieController {
private Map<String, CatalogItem> storage = new HashMap<String, CatalogItem>() {{
storage.put("friends", new CatalogItem("friends", "test", 9));
storage.put("gameofthrones", new CatalogItem("gameofthrones", "test2", 3));
}};
@GetMapping
public Collection<CatalogItem> getAllCatalogs() {
return storage.values();
}
@GetMapping("/{userId}")
public CatalogItem getCatalog(@PathVariable("userId") String userId) {
return storage.get(userId);
}
}
我已经用 CatalogItem 的所有实例初始化了地图。我将您存储userId
为键,将实例存储为值。我定义了两个端点:一个用于获取所有对象,一个用于查找一个对象。
方法getAllCatalogs()
返回所有对象作为响应。要调用此方法,您可以请求/catalog
路径。
方法getCatalog(String userId)
仅返回一个对象以响应您请求的 userId。您只能通过请求/catalog/{userId}
路径获取一个实例。在该方法getCatalog(String userId)
中,我只是通过键(userId)在地图中找到一个实例。
您可以使用另一种解决方案来存储您的对象(内存中、数据库)而不是 Map。
推荐阅读
- python - 带有集成 websocket 客户端的 FastAPI 冻结,我应该如何将它们结合起来?
- json - ADX:看不到使用 JSON 映射提取的结果
- angular - 如何使用带有子组件的 Ng-Bootstrap Nav 作为选项卡?
- c# - 如何使用 C# 删除 Windows 本地组(非活动目录组)?
- excel - Excel - 分隔符:文本到按值分组的列
- c++ - 检查号码是否为 Armstrong Number c++
- reactjs - React 控制表单中文本输入的顺序
- visual-studio-code - VS 代码扩展 - 如何将 WebviewPanel 添加到侧边栏?
- flutter - Flutter如何在测试函数中调用函数响应时模拟函数响应
- java - Java 将地图存储在文件中