如果没有找到@PathVariable可以返回null吗?
-
14-11-2019 - |
题
是否有可能使 @PathVariable
如果路径变量不在 url 中,则返回 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 [示例]
解决方案
它们不能是可选的,不是。如果您需要的话,您需要两种方法来处理它们。
这反映了路径变量的本质 - 它们为空并没有真正的意义。REST 样式的 URL 始终需要完整的 URL 路径。如果您有可选组件,请考虑将其作为请求参数(即使用 @RequestParam
)。这更适合可选参数。
其他提示
正如其他人已经提到的那样,当您明确提到路径参数时,您不能期望它们为空。但是,您可以执行如下操作作为解决方法 -
@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,您可以使用 java.util.Optional,它在 @RequestParam
, @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"
}
}
你总是可以这样做:
@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)
尝试这个方法,它对我有用。
不隶属于 StackOverflow