The optional long parameter 'id' is present but cannot be set to null

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 am getting the following error when issuing an HTTP request for GET /bbct/api/v1.0/card/1

.

The optional long parameter 'id' is present, but cannot be cast to null due to the fact that it is declared as a primitive type.

The proposal is to declare id

how Long

; however, I would prefer not to.

I wonder why Spring considers the parameter to be id

optional? Since I have another method that handles requests when the ID is missing, the ID was necessarily provided if the request was sent to getCard()

.

Here is the complete 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));
    }

}

      

+3


source to share


1 answer


I think what happened is that you (by accident?) Made a request /bbct/api/v1.0/card/

(note the trailing slash at the end) and it will show up in getCard()

insteadgetAllCards()



It would probably be nice to map the id to Long

and set the attribute required = false

to @PathVariable("id")

, then redirect to getAllCards()

. This way you can match both the forward slash suffix and the non-forward slash suffixgetAllCards()

0


source







All Articles