首页 > 解决方案 > 请求映射到列表中的特定项目

问题描述

抱歉,我是 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)
       );
    }

}

标签: spring

解决方案


你可以尝试这样的事情:

@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。


推荐阅读