如果找不到,@ PathVariable可以返回null吗? [英] Can @PathVariable return null if it's not found?
问题描述
如果路径变量不在url中,是否可以使 @PathVariable
返回null?否则我需要做两个处理程序。一个用于 / simple
,另一个用于 / simple / {game}
,但两者都是相同的,如果没有游戏定义我从列表中选择第一个然而如果有游戏参数定义然后我使用它。
Is it possible to make the @PathVariable
to return null if the path variable is not in the url? Otherwise I need to make two handlers. One for /simple
and another for /simple/{game}
, but both do the same just if there is no game defined i pick first one from a list however if there is a game param defined then i use it.
@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
HttpServletRequest request) {
这是我在尝试打开页面时获得的 / simple
:
And this is what I get when trying to open page /simple
:
引起:java.lang.IllegalStateException:在@RequestMapping中找不到@PathVariable [example]
Caused by: java.lang.IllegalStateException: Could not find @PathVariable [example] in @RequestMapping
推荐答案
它们不能是可选的,不是。如果你需要它,你需要两种方法来处理它们。
They cannot be optional, no. If you need that, you need two methods to handle them.
这反映了路径变量的本质 - 它们对于它们来说没有意义。 REST样式的URL始终需要完整的URL路径。如果您有可选组件,请考虑将其作为请求参数(即使用 @RequestParam
)。这更适合于可选参数。
This reflects the nature of path variables - it doesn't really make sense for them to be null. REST-style URLs always need the full URL path. If you have an optional component, consider making it a request parameter instead (i.e. using @RequestParam
). This is much better suited to optional arguments.
这篇关于如果找不到,@ PathVariable可以返回null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!