Spring 3 Web MVC – Friendly URL using RequestMapping variable URI

Following on from a previous tutorial on getting a hello world Spring 3 Web MVC application running in Netbeans here, this tutorial will explain how to achieve friendly URL’s incorporating variables.





From the previous example application we have the following jsp called viewdemo.jsp

The Person bean is:

And the controller is:


Now add the following to the controller:




Note the RequestMapping value now has /{} on the end of it. Also note that the RequestMethod is GET for obvious reasons. value=”name” is not strictly necessary as there is only PathVariable, spring gets the picture. Note that when using it however, value =”matchMe” and what’s in /{matchMe} must match.

Now in demo.jsp, we’ll create a link that will invoke this method passing in the ‘name’ parameter:

The ‘Show Default ‘ link will call controller method

returning a person with ‘Jack’ as the name hardcoded into it. The ‘Show Mary’ link will call controller method

Hence the name parameter is passed in and thus revealed as the page is rendered.

For setting this project up in full, please refer to this tutorial

Note that there can be many parameters in the @RequestMapping(value=””) annotation.


The link to this then becomes


Now, a rather unfortunate problem arises here: Click any of the links once and everything is ok, click the link again and it’s clear that an extra /person is in the url http://localhost:8084/HelloSpring/person/person/Mary

This is a common problem and I’ll address it in a future blog but for now, it can be corrected easily by specifying the full context path in each link as so:


Now it’s possible to click eack link as often as one likes.

Hope this tutorial on Spring 3 Web MVC @PathVariable with @RequestMapping variable URI was helpful…..