Spring MVC URI Template Example

Monday, April 18th, 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. As I was trawling through the source code I noticed “some wierd” syntax: “/{xxxx}” (which of course I had to look up!).

Most of the following is based upon the excellent Spring Documentation. I’ve lifted and rewritten the parts I require to serve as a condensed “aide-mémoire”.

Description

A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI.

For example, the URI Template

http://foo.bar.com/products/{productName}

contains the variable “productName”. If we assign the variable the value “widgetA”, the URI Template yields:

http://foo.bar.com/products/widgetA

Example

@Controller
public class ProductController {
    @RequestMapping(value="/products/{productName}, method = RequestMethod.GET)
    public String getProductDetails(@PathVariable("productName") String productName, Model model) {
        Product product = this.productService.getProduct(productName);
        model.addAttribute("productDetails", product);
        return "productDetailPage";
    }
}

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

Tags: , ,
Posted in: Spring



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>