Spring MVC 3.x @PathVariable Annotation Example

Friday, April 15th, 2011

Background

So, I’m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the “@PathVariable” annotation (which of course I had to look up!).

Example

Imagine you’d like to create a controller that would allow users to see view products by using a URL such as http://foo.bar.com/productDetails/someProduct

e.g.

http://foo.bar.com/productDetails/widgetA - display details for widgetA
http://foo.bar.com/productDetails/widgetB - display details for widgetB

The @PathVariable annotation makes this easy…

package foo.bar;

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

@Controller
public class ShowProductController {
	 
    @RequestMapping("/productDetails/{productName}") // Handle any request of the form "/productDetails/XXXXX"
    public String showProduct(Model model, @PathVariable("productName") String productName) {
        model.addAttribute("productName", productName);
        return "showProduct"; // viewname
    }
}

What just happened?

Note the {productName} in the @RequestMapping – this is the path variable. The @PathVariable annotation on the next line captures the value and binds it to the method argument

You can leave a response, or trackback from your own site.

Tags: , ,
Posted in: Development, Examples



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>