@pathvariable이 발견되지 않으면 null 수 있습니다.
-
14-11-2019 - |
문제
경로 변수가 URL에 있지 않으면 @PathVariable
가 null를 반환 할 수 있습니까?그렇지 않으면 두 개의 핸들러를 만들어야합니다./simple
및 /simple/{game}
에 대해 다른 하나는 둘 다 정의되지만 둘 다 동일하게 수행합니다. 그러나 목록에서 첫 번째를 선택하지만 게임 파라미터가 정의 된 경우 i를 사용합니다.
@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
HttpServletRequest request) {
.
페이지를 열려고 할 때 얻을 수있는 것입니다.
로 인해 java.lang.IllegalStateException : @RequestMapping의 @PathVariable [예제]를 찾을 수 없습니다
해결책
They cannot be optional, no. If you need that, you need two methods to handle them.
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.
다른 팁
As others have already mentioned No you cannot expect them to be null when you have explicitly mentioned the path parameters. However you can do something like below as a workaround -
@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"
}
}
If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam
, @PathVariable
, @RequestHeader
and @MatrixVariable
in 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"
}
}
You could always just do this:
@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)
Try this approach, it worked for me.