I have two methods in my 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)
I get the following error when issuing a HTTP request for GET /bbct/api/v1.0/card/1
.
Optional long parameter 'id' is present but cannot be translated into a null value due to being declared as a primitive type.
The suggestion is to declare id
as a Long
; however, I'd prefer to not do this.
I wonder why Spring thinks the id
parameter is optional? 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()
.
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()
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()
. This way you can map both slash-suffixed and non-slash-suffixed version of getAllCards()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.