2011-03-30 65 views
18

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

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

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

产生的原因:java.lang.IllegalStateException:找不到@PathVariable [示例]在@RequestMapping

回答

21

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

这反映了路径变量的性质 - 它们没有意义,它们是空的。 REST风格的URL总是需要完整的URL路径。如果您有可选组件,请考虑将其设为请求参数(即使用@RequestParam)。这更适合于可选参数。

+0

谢谢! :)将检查'@ RequestParam'。 – Rihards 2011-03-30 23:55:49

+0

但是,正弦v4.3.3 Spring支持'@PathVariable(value =“siteId”,required = false)String siteId',尽管我还没有找到一种方法*不提供路径变量*或将其留空或空。 – Alex 2017-09-15 14:08:49

17

你总是可以只是这样做:

@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) { 
17

正如其他人已经提到不,你不能指望当你已经明确提到的路径参数,它们是空的。如果你在Spring MVC中

使用Spring 4.1和Java 8可以使用java.util.Optional这是在 @RequestParam支持, @PathVariable@RequestHeader@MatrixVariable

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

- 但是你可以做类似下面的解决方法

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

谢谢,这应该是被接受的答案 – membersound 2016-02-04 16:43:18

+0

谢谢,这是一个更好的解决方案。 – drafterr 2018-01-23 07:30:47

相关问题