Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate URI inside a controller in Spring 3

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?

like image 233
Nanocom Avatar asked Jan 06 '12 17:01

Nanocom


People also ask

What is UriComponentsBuilder in Java?

public class UriComponentsBuilder extends Object implements UriBuilder, Cloneable. Builder for UriComponents . Typical usage involves: Create a UriComponentsBuilder with one of the static factory methods (such as fromPath(String) or fromUri(URI) )

What is difference between controller and RestController?

@Controller is used to mark classes as Spring MVC Controller. @RestController annotation is a special controller used in RESTful Web services, and it's the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation.


1 Answers

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.

like image 116
Christopher Yang Avatar answered Dec 24 '22 20:12

Christopher Yang