Spring MVC URI template example

A URI Template is a string containing one or more variables which can be replaced by values to obtain a URL.

URI Templates are used to map requests with @RequestMapping when implementing controllers.

In this example, we will see three cases of using the URI Template patterns.


1. Technologies used

  • Spring 4.2.0.RELEASE
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.6
  • Tomcat 7.0


2. Project structure



3. Project dependencies

We add Spring MVC dependencies in Maven’ s pom.xml file as shown below :


4. Controller

  • Using simple URI Template pattern on controller and/or method level :

We have used the @PathVariable annotation to bind the method arguments to the URI template variables (technology and module).

The URI template variable name must match the method argument name, otherwise we can specify the matching URI template variable name in the annotation : @PathVariable("module")


  • Using URI Template pattern with regular expressions :

We can use regular expressions when we need more precision in defining URI template variables. The syntax is {variableName:regex} where variableName is the variable name and regex defines the regular expression.

We will try to define the URL : “/dependencies/spring-web-4.2.0.RELEASE.jar”


  • Using URI Template pattern with wild cards :


The following is the complete implementation of our controller :


5. JSP view

File : index.jsp

We have created three links to test the three cases of using the URI template patterns : simple URI, URI with regular expression and URI with wild card.

File : result.jsp

By using the message model variable, we can display the values of the URI template variables in each URL.


6. Spring MVC configuration

File : mvc-dispatcher-servlet.xml


7. Web app configuration

File : web.xml


8. Test It

URL : http://localhost:8080/SpringMVC-URI-Template-Example/tech/Spring/index

SpringMVC-URI-Template-Example 1

When we click the first link :


The second link :


And the third link :


Download source code