Java, Software Development, Spring

Spring MVC PathVariable Annotation

Sometimes we want to send values to our web application as the path of the URL (or URI) path. For example, /tenants/123 where value 123 represents a tenant Id. To independently access the value in Spring MVC, we use the PathVariable annotation.

In this post, we are using Spring 5.

PathVariable Annotation Lets Us Pick Part of an URL as the value

How does the Spring MVC PathVariable annotation enable us to pick a part of an URL as a value? To use the PathVariable annotation, we need to work closely with some annotations – RequestMapping or XXMapping (GetMapping, PostMapping, etc.).

Consider the following example where we use a named placeholder – {id} – in the URI. Spring automatically ties up the placeholder with the variable name id, which also uses the PathVariable annotation.

But we do not want to do that! If someone changes the parameter variable id to something else, the code will not work. A safer approach is to use the placeholder’s name as an argument to the PathVariable annotation. Consider the following code example.

More Advanced Mappings in Spring MVC with PathVariable

The codes we showed in the previous section are for methods. What if we extract a path value from a URL we placed on the class level? Consider the following.

Notice that we are also using multiple PathVariable annotations to access the values for personId and petId.

Uncommon Mapping Styles with Spring MVC PathVariable

If we do not want to use multiple PathVariable annotations in our controller, we capture the values as Map. However, this may restrict us to using a single type for the values, e.g., Map<String, String>.

Consider the following codes.

Lastly, we can use regular expressions with the PathVariable annotation in Spring MVC. Consider the following example.

In the code example, we essentially split a port of the URL into the year, month, and date values.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like