如果路径变量不在 url 中,是否可以使 @PathVariable
返回 null?否则我需要做两个处理程序。一个用于/simple
,另一个用于/simple/{game}
,但如果没有定义游戏,两者都做同样的事情我从列表中选择第一个但是如果有是定义的游戏参数然后我使用它。
@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
HttpServletRequest request) {
这就是我尝试打开页面时得到的结果/simple
:
Caused by: java.lang.IllegalStateException: Could not find @PathVariable [example] in @RequestMapping
最佳答案
正如其他人已经提到的那样,当您明确提到路径参数时,您不能期望它们为空。但是,您可以执行以下操作作为解决方法 -
@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"
}
}
如果您使用 Spring 4.1 和 Java 8,您可以使用 @RequestParam
中支持的 java.util.Optional , @PathVariable
, @RequestHeader
和 @MatrixVariable
在 Spring 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"
}
}
关于java - 如果找不到,@PathVariable 可以返回 null 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5493767/