如果找不到,@ PathVariable可以返回null吗?

Rih*_*rds 27 java path-variables spring-annotations spring-3

@PathVariable如果路径变量不在url中,是否可以使返回null?否则我需要做两个处理程序.一个用于/simple另一个/simple/{game},但两者都做同样的事情,如果没有定义游戏我从列表中选择第一个然而如果有游戏参数定义然后我使用它.

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
            HttpServletRequest request) {
Run Code Online (Sandbox Code Playgroud)

这是我在尝试打开页面时得到的/simple:

引起:java.lang.IllegalStateException:在@RequestMapping中找不到@PathVariable [example]

ska*_*man 32

它们不能是可选的,不是.如果需要,您需要两种方法来处理它们.

这反映了路径变量的本质 - 它们对于它们无效是没有意义的.REST样式的URL始终需要完整的URL路径.如果您有可选组件,请考虑将其作为请求参数(即使用@RequestParam).这更适合于可选参数.

  • 但是,sine v4.3.3 Spring支持`@PathVariable(value =“ siteId”,required = false)字符串siteId`,尽管我还没有找到*不提供路径变量*或将其留为空白或为空的方法。 (2认同)
  • @Alex虽然可以将“required”参数设置为“false”,但仍然需要提供路径参数,否则将引发异常。 (2认同)

Ani*_*kur 28

正如其他人已经提到的那样,当您明确提到路径参数时,您不能指望它们为空.但是你可以做下面的事情作为一种解决方法 -

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable Map<String, String> pathVariablesMap,
            HttpServletRequest request) {
    if (pathVariablesMap.containsKey("game")) {
        //corresponds to path "/simple/{game}"
    } else {
        //corresponds to path "/simple"
    }           
}
Run Code Online (Sandbox Code Playgroud)

如果您在使用Spring 4.1和Java 8可以使用java.util.Optional这是在支持@RequestParam,@PathVariable,@RequestHeader@MatrixVariableSpring MVC中

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable Optional<String> game,
            HttpServletRequest request) {
    if (game.isPresent()) {
        //game.get()
        //corresponds to path "/simple/{game}"
    } else {
        //corresponds to path "/simple"
    }           
}
Run Code Online (Sandbox Code Playgroud)


小智 19

你总是可以这样做:

@RequestMapping(value = "/simple", method = RequestMethod.GET)
public ModelAndView gameHandler(HttpServletRequest request) {
    gameHandler2(null, request)
}

@RequestMapping(value = "/simple/{game}", method = RequestMethod.GET)
public ModelAndView gameHandler2(@PathVariable("game") String game,
        HttpServletRequest request) {
Run Code Online (Sandbox Code Playgroud)