Вопрос

Можно ли сделать генеракодицетагкод для возврата NULL, если переменная пути не в URL-адреса?В противном случае мне нужно сделать два обработчика.Один для @PathVariable и другой для /simple, но оба делают то же самое только в том случае, если нет определенной игры, я выбираю первый из списка, однако, если есть определенный параметр игры, я использую его.

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

И это то, что я получаю, когда пытаясь открыть страницу GeneracodicCode:

вызвано: java.lang.illegalstateException: не удалось найти @ dathvariable [пример] в @requestmapping

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top