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

Excuse me for asking such a simple question, as I am new to Spring MVC 3.0. I have read the documentation from the Spring website several times. Here is a snippet of code that I will discuss below: -

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

If I intend to use a URI pattern based on this example, it is always preferable that the @PathVariable type be String, although I expect it to be a different type, such as int? The documentation says that the @PathVariable annotation can be of any simple type, but if Spring cannot convert the invalid petId to int (for example, the user enters some characters instead of numbers), it will throw a TypeMismatchException.

So when is the validator valid? Should I leave all @PathVariable String types and have a validator to check for String values, and if there is no validation error, will it explicitly convert String to the desired type?

Thanks.

+6
java spring spring-mvc
source share
2 answers
  • Let @PathVariable be the type you expect, not necessarily String
  • Have a well-tuned error page. If the user decides to write something in the URL, he should be aware of the "consequences".
+6
source share

you said

but if Spring cannot convert the invalid petId to int , it will throw a TypeMismatchException .

Ok But you can handle the above 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 } 

@ The signature of the excceptionHandler handler method is flexibe, see here

+7
source share

All Articles