[英]Optional long parameter 'id' is present but cannot be translated into a null value
I have two methods in my Spring controller: 我的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)
I get the following error when issuing a HTTP request for GET /bbct/api/v1.0/card/1
. 发出
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'存在但由于被声明为基本类型而无法转换为空值。
The suggestion is to declare id
as a Long
; 建议将
id
声明为Long
; however, I'd prefer to not do this. 但是,我宁愿不这样做。
I wonder why Spring thinks the id
parameter is optional? 我想知道为什么Spring认为
id
参数是可选的? Since I have a another method which processes requests when the id is missing, the id was certainly supplied, if the request is dispatched to getCard()
. 因为我有另一个方法在id丢失时处理请求,所以如果将请求分派给
getCard()
,则肯定提供了id。
Here is the full 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));
}
}
I think what happened was you (inadvertently?) made request to /bbct/api/v1.0/card/
(pay attention to the trailing slash at the end) and it gets mapped into getCard()
instead of getAllCards()
我想发生的事情是你(无意中?)向
/bbct/api/v1.0/card/
发出请求(注意结尾处的尾部斜线)并将其映射到getCard()
而不是getAllCards()
Probably it's a good idea to map the id into Long
and set the required = false
attribute on @PathVariable("id")
, then do a redirect into getAllCards()
. 将id映射到
Long
并在@PathVariable("id")
上设置required = false
属性可能是个好主意,然后重定向到getAllCards()
。 This way you can map both slash-suffixed and non-slash-suffixed version of getAllCards()
这样你就可以映射
getAllCards()
斜杠后缀和非斜杠后缀版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.