Spring MVC 3.0:String是@PathVariable的首选类型吗?

lim*_*imc 6 java spring spring-mvc

请原谅我在这里提出这样一个简单的问题,因为我是Spring MVC 3.0的新手.我一直在阅读spring source website的文档几次.这是我在下面的问题中引用的代码片段: -

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

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

那么,验证器什么时候开始发挥作用?我是否将所有@PathVariable类型保留为String并使用验证器对String值执行验证,如果没有验证错误,则将String显式转换为所需类型?

谢谢.

Art*_*ald 7

你说

但是如果Spring 无法将无效的petId转换为int,它将抛出一个TypeMismatchException.

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

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

@ExceptionHandler处理程序方法签名是flexibe,请参见此处


Boz*_*zho 6

  1. 让它@PathVariable成为你期望的类型,不一定String
  2. 有一个很好的自定义错误页面.如果用户决定在URL中写入内容,他应该知道"后果".