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 numbers), 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.
3 version, @PathVariable annotation has required attribute, to specify it is mandatorily required in URI. The default value for this attribute is true if we make this attribute value to false, then Spring MVC will not throw an exception.
The @PathVariable annotation is used for data passed in the URI (e.g. RESTful web services) while @RequestParam is used to extract the data found in query parameters. These annotations can be mixed together inside the same controller. @PathParam is a JAX-RS annotation that is equivalent to @PathVariable in Spring.
1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.
The @PathVariable annotation is used to extract the value from the URI. It is most suitable for the RESTful web service where the URL contains some value. Spring MVC allows us to use multiple @PathVariable annotations in the same method. A path variable is a critical part of creating rest resources.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With