java - Spring MVC 3.0 : Is String the preferred type to be used for @PathVariable?

标签 java spring spring-mvc

请原谅我在这里问这么简单的问题,因为我是 Spring MVC 3.0 的新手。我一直在阅读 spring 源网站上的文档几次。这是我将在下面的问题中引用的代码片段:-

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

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

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

谢谢。

最佳答案

你说

but if Spring is unable to convert the invalid petId into an int, it will throw a TypeMismatchException.

好的。但是如果需要,您可以通过@ExceptionHandler 注释在 Controller 中处理引发的异常

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

@ExceptionHandler 处理程序方法签名是灵活的,参见 here

关于java - Spring MVC 3.0 : Is String the preferred type to be used for @PathVariable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3460606/

相关文章:

具有多个标识符的 Spring 和 @JsonView

java - Wildfly 域模式附加验证问题

java - fragment 中的 RecyclerView 无法正常工作

java - Android 中 DisplayMetrics 声明错误中的 getWindowManager 错误

java - Java 中的素数生成线程打印两次

spring - 尝试设置 PSQL,我收到此错误 :

spring - AWS Lambda Java 函数 Spring 上下文初始化

java - Spring thymeleaf 模板在添加 CORS 配置后不起作用

java - Tomcat 和 Spring MVC - 未找到具有 URI 的 HTTP 请求的映射

java - 我的 Maven 构建中缺少 AbstractAnnotationConfigDispatcherServletInitializer