Sunday, January 9, 2011

Converting Relative to Absolute URL's

The very first time I used the ExpandPath() function I remember wondering why there was not a similar function for expanding url's. At some point later, I did sit down and write a very rudimentary ExpandURL function. I have long since forgotten the code. But I do have a vague recollection of an ugly series of strings functions. Well the other day I came across a tip on that would have made it much easier:

You simply pass in an object representing the base url (ie and a string representing the relative path (ie "../../somePage.cfm"). The class normalizes the paths and returns an absolute url. In this example it would be: With a little effort it could be used to create a custom ExpandURL() function.

   ... or using the base url of current request 
   <cfset theBaseURL = getPageContext().getRequest().getRequestURL()>
<cfset theBaseURL = "" />
<cfset theRelativeURL = "../../somePage.cfm" />
<cfset baseURL = createObject("java", "").init( theBaseURL ) />
<cfset absURL = createObject("java", "").init( baseURL, theRelativeURL ) />

   <p>theBaseURL = #theBaseURL#</p>
   <p>theRelativeURL = #theRelativeURL#</p>
   <p>absURL = #absURL.toString()#</p> 

Now obviously I am glossing over a lot.  There are definitely nuances to be aware of, but you can find a complete description of how the paths are resolved in the java api (and referenced specifications for url's and uri's). This method is not perfect, but overall it is a lot more robust and elegant than using string functions.


  © Blogger templates The Professional Template by 2008

Header image adapted from atomicjeep