views:

82

answers:

2

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.

+2  A: 
  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".
Bozho
This approach works if the user constructs the URL themselves. However, I'm not sure how this will work if the value for petId comes from an open text field submitted from a form.
limc
then that is not a `@PathVariable`, but a `@RequestParam`. And the validation should be done client-side, in addition to server-side
Bozho
Thanks for your insightful explanation, I guess I got confused between @pathvariable and @requestparam.
limc
@Bozho I gives you UP vote (+1) just because you have said: He should be aware of the "consequences".
Arthur Ronald F D Garcia
+2  A: 

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

Arthur Ronald F D Garcia
and my upvote to you goes about the @ExceptionHandler, which I didn't know of ;)
Bozho