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

前端 未结 6 1637
失恋的感觉
失恋的感觉 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:40

    As others have already mentioned No you cannot expect them to be null when you have explicitly mentioned the path parameters. However you can do something like below as a workaround -

    @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
    public ModelAndView gameHandler(@PathVariable Map pathVariablesMap,
                HttpServletRequest request) {
        if (pathVariablesMap.containsKey("game")) {
            //corresponds to path "/simple/{game}"
        } else {
            //corresponds to path "/simple"
        }           
    }
    

    If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam, @PathVariable, @RequestHeader and @MatrixVariable in Spring MVC

    @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
    public ModelAndView gameHandler(@PathVariable Optional game,
                HttpServletRequest request) {
        if (game.isPresent()) {
            //game.get()
            //corresponds to path "/simple/{game}"
        } else {
            //corresponds to path "/simple"
        }           
    }
    

提交回复
热议问题