Spring MVC Building URIs Example

Spring MVC provides ways to build and encode URI’s from Controller, methods and views. Using UriComponentsBuilder and UriComponents we can create uri.

The UriComponents can also be build using individual components like hostName, port, path.

Spring MVC Building URI from Controller methods

As seen from the above code snippets, we can also build uri from the methods of controllers.
If you have a controller

You can use the below code to generate URI

Here we provided the actual values.If the method had more arguments you can supply null for arguments not needed for the URL. In general only @PathVariable and @RequestParam arguments are relevant for constructing the URL.

This URI building technique is useful in mock testing your app.

Spring MVC Building URI from Views

We can also build URI to our annotated Controller from the view pages.

Every @RequestMapping is assigned a default name based on the capital letters of the class and the full method name. For example, the method getFoo in class FooController is assigned the name “FC#getFoo”. This strategy can be replaced or customized by creating an instance of HandlerMethodMappingNamingStrategy and plugging it into your RequestMappingHandlerMapping. The default strategy implementation also looks at the name attribute on @RequestMapping and uses that if present. That means if the default mapping name assigned conflicts with another (e.g. overloaded methods) you can assign a name explicitly on the @RequestMapping. Source

Suppose we have the same controller as we did for our earlier example

You can create a link in your JSP as below.

Note : the arg has 2 params. 1st the position of the pathvariable or RequestParam and it starts from 0. 2nd is the actual value of the pathvariable or RequestParam.