Can @PathVariable return null if it's not found?

前端 未结 6 1642
失恋的感觉
失恋的感觉 2020-12-13 14:17

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

6条回答
  •  余生分开走
    2020-12-13 14:48

    We can write multiple methods in controllers with explicit mapping with the path variable combination to exclude the optional variables (if using old version of Spring)

    In my scenario wanted to develop an API to get recycle value for old device where parameters could be brand, model and network however network is an option one.

    One option to handle this was use network as a request parameter instead of pathVariable. for e.g. /value/LG/g3?network=vodafone however I didn't like this approach.

    for me the more cleaner one was to use below /refurbValue/LG/g3 /refurbValue/LG/g3/vodafone

       @RequestMapping(value = "/refurbValue/{make}/{model}/{network}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    def getRefurbValueByMakeAndModelAndNetwork(@PathVariable String make, @PathVariable String model, @PathVariable String network ) throws Exception {
        //logic here
    }
    
    @RequestMapping(value = "/refurbValue/{make}/{model}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    def getRefurbValueByMakeAndModel(@PathVariable String make, @PathVariable String model) throws Exception {
        //logic here
    }
    

    In the above example, both controller can use the same service method and handling of the parameter can be done. In my case I was using Groovy so it was easy to use with optional parameter like

    Map getRefurbValue(String brand, String model, String network="")

提交回复
热议问题