gpt4 book ai didi

java - 存在可选长参数 'id',但无法转换为空值

转载 作者:行者123 更新时间:2023-12-02 09:06:24 24 4
gpt4 key购买 nike

我的 Spring Controller 中有两个方法:

    @RequestMapping(method = RequestMethod.GET, value = CARD_PATH)
public @ResponseBody List<BaseballCard> getAllCards()

@RequestMapping(method = RequestMethod.GET, value = CARD_PATH + "/{id}")
public BaseballCard getCard(@PathVariable("id") long id)

在发出 GET/bbct/api/v1.0/card/1 HTTP 请求时出现以下错误。

Optional long parameter 'id' is present but cannot be translated into a null value due to being declared as a primitive type.

建议将id声明为Long;但是,我不想这样做。

我想知道为什么Spring认为id参数是可选的?由于我有另一种在 id 丢失时处理请求的方法,因此如果请求被分派(dispatch)到 getCard(),则肯定会提供 id。

这是完整的 Controller :

@Controller
public class BaseballCardController {

private static final String CARD_PATH = "/bbct/api/v1.0/card";

private List<BaseballCard> cards = new ArrayList<BaseballCard>();

@RequestMapping(method = RequestMethod.POST, value = CARD_PATH)
public @ResponseBody
BaseballCard addCard(@RequestBody BaseballCard card) {
cards.add(card);
card.setId(cards.size());
return card;
}

@RequestMapping(method = RequestMethod.GET, value = CARD_PATH)
public @ResponseBody List<BaseballCard> getAllCards() {
return cards;
}

@RequestMapping(method = RequestMethod.GET, value = CARD_PATH + "/{id}")
public BaseballCard getCard(@PathVariable("id") long id) {
return cards.get((int)(id - 1));
}

}

最佳答案

我认为发生的事情是您(无意中?)向 /bbct/api/v1.0/card/ 发出请求(注意末尾的斜杠),它被映射到getCard() 而不是 getAllCards()

将 id 映射到 Long 并在 @PathVariable("id") 上设置 required = false 属性可能是个好主意,然后重定向到 getAllCards()。这样您就可以映射 getAllCards()

的斜杠后缀和非斜杠后缀版本

关于java - 存在可选长参数 'id',但无法转换为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com