Can @PathVariable return null if it's not found?

前端 未结 6 1632
失恋的感觉
失恋的感觉 2020-12-13 14:17

Is it possible to make the @PathVariable to return null if the path variable is not in the url? Otherwise I need to make two handlers. One for /simple

6条回答
  •  青春惊慌失措
    2020-12-13 14:42

    I just tested this just now, but by combining the above solution i got this:

    @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
    public ModelAndView gameHandler(@PathVariable(value = "game", required = false) String example,
                                    HttpServletRequest request) {
        if (example != null) {
            //...
        } else {
            //pick first, ...
        }
    }
    

    Now when you use "/simple", String example will be null instead of throwing Exception.

    Short solution, no fancy Optional<> or Map<>

提交回复
热议问题