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

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

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

这是我在尝试打开页面/simple

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

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

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

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

 @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" } } 

如果您使用的是Spring 4.1和Java 8,则可以使用@PathVariable@RequestHeader @MatrixVariable@PathVariable@MatrixVariable支持的java.util.Optional

 @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" } } 

你可以随时这样做:

 @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) { 
 @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET) public ModelAndView gameHandler(@PathVariable(value="example",required = false) final String example) 

尝试这种方法,它对我有用。