开发者

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

开发者 https://www.devze.com 2023-01-11 07:25 出处:网络
Pardon me for asking such a simple question here as I\'m new to Spring MVC 3.0. I have been reading the documentation from spring source website a few times. Here\'s a code snippet that I\'ll refer to

Pardon me for asking such a simple question here as I'm new to Spring MVC 3.0. I have been reading the documentation from spring source website a few times. Here's a code snippet that I'll refer to for my question below:-

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

If I intend to use the URI template based on this example, is it always preferable to set up the @PathVariable type to be String even though I'm expecting it to be other type, such as, an int? The documentation says the @PathVariable annotation can be of any simple type, but if Spring is unable to convert the invalid petId into an int (for example, user enters some characters instead of numbe开发者_Go百科rs), it will throw a TypeMismatchException.

So, when does the validator comes into play? Do I leave all the @PathVariable types to be String and have the validator to perform the validation on the String values, and if there's no validation error, then explicitly convert the String to the desired type?

Thank you.


You said

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

Ok. But you can handle raised exceptions in the controller via the @ExceptionHandler annotation if you want

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

@ExceptionHandler handler method signature is flexibe, See here


  1. Let the @PathVariable be the type you expect, not necessarily String
  2. Have a well customized error page. If the user decides to write something in the URL, he should be aware of the "consequences".
0

精彩评论

暂无评论...
验证码 换一张
取 消