[英]Optional long parameter 'id' is present but cannot be translated into a null value
我的Spring控制器中有两个方法:
@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请求时出现以下错误。
可选的长参数'id'存在但由于被声明为基本类型而无法转换为空值。
建议将id
声明为Long
; 但是,我宁愿不这样做。
我想知道为什么Spring认为id
参数是可选的? 因为我有另一个方法在id丢失时处理请求,所以如果将请求分派给getCard()
,则肯定提供了id。
这是完整的控制器:
@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()
斜杠后缀和非斜杠后缀版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.