【问题标题】:Can @PathVariable return null if it's not found?如果找不到,@PathVariable 可以返回 null 吗?
【发布时间】:2011-07-26 12:17:00
【问题描述】:

如果路径变量不在 url 中,是否可以使 @PathVariable 返回 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 [示例]

【问题讨论】:

    标签: java spring-3 spring-annotations path-variables


    【解决方案1】:

    它们不能是可选的,不。如果需要,则需要两种方法来处理它们。

    这反映了路径变量的性质——它们为空并没有任何意义。 REST 样式的 URL 始终需要完整的 URL 路径。如果您有一个可选组件,请考虑将其设为请求参数(即使用@RequestParam)。这更适合可选参数。

    【讨论】:

    • 然而,sine v4.3.3 Spring 支持@PathVariable(value = "siteId", required = false) String siteId 虽然我还没有找到一种方法不提供路径变量或将其留空或留空。
    • @Alex 虽然可以将required参数设置为false,但仍需要提供路径参数,否则会抛出异常。
    【解决方案2】:

    你总是可以这样做:

    @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) {
    

    【讨论】:

      【解决方案3】:

      正如其他人已经提到的那样,当您明确提到路径参数时,您不能期望它们为空。但是,您可以执行以下操作作为解决方法 -

      @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,它在 Spring MVC 中的 @RequestParam、@PathVariable、@RequestHeader 和 @MatrixVariable 中受支持

      @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"
          }           
      }
      

      【讨论】:

        【解决方案4】:
        @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
        public ModelAndView gameHandler(@PathVariable(value="example",required = false) final String example)
        

        试试这个方法,它对我有用。

        【讨论】:

          【解决方案5】:

          我刚刚测试了这个,但是通过结合上面的解决方案我得到了这个:

          @RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
          public ModelAndView gameHandler(@PathVariable(value = "game", required = false) String example,
                                          HttpServletRequest request) {
              if (example != null) {
                  //...
              } else {
                  //pick first, ...
              }
          }
          

          现在当你使用“/simple”时,String 示例将为 null 而不是抛出异常。

          简短的解决方案,没有花哨的 Optional 或 Map

          【讨论】:

            【解决方案6】:

            我们可以在控制器中编写多个方法,通过路径变量组合的显式映射来排除可选变量(如果使用旧版本的 Spring)

            在我的场景中,我想开发一个 API 来获得旧设备的回收价值,其中参数可以是品牌、型号和网络,但网络是一种选择。

            处理此问题的一个选项是使用网络作为请求参数而不是 pathVariable。 例如/value/LG/g3?network=vodafone 但是我不喜欢这种方法。

            对我来说,更清洁的是在下面使用 /refurbValue/LG/g3 /refurbValue/LG/g3/沃达丰

               @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
            }
            

            在上面的例子中,两个控制器可以使用相同的服务方法并且可以完成参数的处理。就我而言,我使用的是 Groovy,因此它很容易与可选参数一起使用,例如

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

            【讨论】:

              猜你喜欢
              • 2012-07-06
              • 2016-10-17
              • 2010-11-10
              • 2023-03-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多