Get the URL of a Page in Tapestry 5

Sometimes your program will need to get the full URL of a page to send in an email, share on Facebook or run through a URL shortener to send to Twitter. You can do this by injecting the HTTPRequest and the building a string representation of the URL manually, but this is a lot more work that it needs to be. Here is a simple way to do it using Tapestry’s PageRenderLinkSource and a Link object.

@Inject
PageRenderLinkSource linkSource

/**
 * Return a string with the full URL of MyPage with a 
 * context of 5.
 */
public String getPageURL() {
	Link link = linkSource.createPageRenderLinkWithContext("MyPage", 5);
	return link.toAbsoluteURI();
}

I’ve hard coded the value 5 as the context–you’d normally set that based on whatever you are wanting to share. This method will return a link to MyPage with a context of 5, so it will probably look something like: http://www.myserver.com/MyPage/5. One of the nice things about this solution is that it will automatically handle things if your application needs to use a URL like: http://www.myserver.com/myapp/MyPage/5

About 

One Reply to “Get the URL of a Page in Tapestry 5”

Leave a Reply

Your email address will not be published.