代码之家  ›  专栏  ›  技术社区  ›  limc

springmvc3.0:String是@PathVariable的首选类型吗?

  •  6
  • limc  · 技术社区  · 14 年前

    请原谅我在这里问了这么一个简单的问题,因为我对springmvc3.0还不熟悉。我已经阅读了几次spring源代码网站上的文档。下面是一段代码片段,我将参考它来回答我的问题below:-

    @RequestMapping("/pets/{petId}")
    public void findPet(@PathVariable String petId, Model model) {    
    // implementation omitted
    }
    

    如果我打算基于这个示例使用URI模板,那么即使我希望@PathVariable类型是其他类型(例如int),是否总是最好将其设置为String?文档中说@PathVariable注释可以是任何简单的类型,但是如果Spring无法将无效的petId转换成int(例如,用户输入一些字符而不是数字),它将抛出typemissmatchexception。

    非常感谢。

    2 回复  |  直到 14 年前
        1
  •  6
  •   Bozho    14 年前
    1. @PathVariable 做你想要的类型,不一定 String
    2. 有一个良好的自定义错误页。如果用户决定在URL中写一些东西,他应该意识到“后果”。
        2
  •  7
  •   Arthur Ronald    14 年前

    你说过

    但如果春天 无法转换无效的petId 变成整数, 它将抛出TypeMismatchException .

    好 啊。但如果需要,可以通过@ExceptionHandler注释处理控制器中引发的异常

    @ExceptionHandler(TypeMismatchException.class)
    public String handleIOException(TypeMismatchException e, HttpServletRequest request) {
        // handle your Exception right here
    }
    

    @ExceptionHandler方法签名为flexibe,请参阅 here