Thursday, June 9, 2011

Using @PathVariable

Let's say that you are creating an user account-based web application in Spring 3.0. You would like to create a controller that would allow users to see each other's profile by using a URL such as
http://myapp/profile/username.

For example:
http://myapp/profile/Juan would show user Juan's profile.
http://myapp/profile/Gaby would show user Gaby's profile.


Spring 3.0's annotated controllers make this kind of mapping easy with the new @PathVariable mapping. As you can see, the RequestMapping for the showProfile method has something a bit unusual: {username}
This is a PathVariable, and it means that this method will serve any request of the format "/profile/someUserName"

We capture the actual username in the next line using the @PathVariable annotation and store it in the variable
final String username
Now we can use it however we want!
Viva Spring framework!!!

No comments:

Post a Comment