How to generate URI inside a controller in Spring 3

Nanocom picture Nanocom · Jan 6, 2012 · Viewed 17.2k times · Source

I use spring 3.0 and I have a really simple question but didn't find any answer on the internet. I want to generate a path (an URI) just like in my JSPs:

<spring:url value="/my/url" />

But inside a controller. What is the related service to use? Thanks!

Edit: May it be related with this: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-resourceloader ? Ain't there a better solution for this?

Answer

Christopher Yang picture Christopher Yang · Dec 10, 2012

Rossen's suggestion is gold.

There's also the ServletUriComponentsBuilder class from 3.1 that builds URLs from current request in static fashion. For example:

ServletUriComponentsBuilder.fromCurrentContextPath().path("/my/additional/path").build().toUriString();

It's the closest thing to <spring:url> in servlet.