Using the @PathVariable annotation in Spring MVC 3.0

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://mysite/profile/username.  For example:

http://mysite/profile/Adam  would show user Adam’s profile.

http://mysite/profile/Baker would show user Baker’s profile.

Spring 3.0’s annotated controllers make this kind of mapping easy with the new @PathVariable mapping.

package com.technologicaloddity.hellowebapp;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

public class ShowProfileController {

    public String showProfile(Model model, @PathVariable("username") String username) {
        model.addAttribute("username", username);
        return "showProfile"; // the view name

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 String username.  Now we can use it however we want!