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 stackoverflow.com that would have made it much easier: java.net.URL.
You simply pass in an object representing the base url (ie http://www.mysite.com/blog/archive/) and a string representing the relative path (ie "../../somePage.cfm"). The java.net.URL class normalizes the paths and returns an absolute url. In this example it would be: http://www.mysite.com/somePage.cfm. 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 = "http://www.mysite.com/blog/archive/" /> <cfset theRelativeURL = "../../somePage.cfm" /> <cfset baseURL = createObject("java", "java.net.URL").init( theBaseURL ) /> <cfset absURL = createObject("java", "java.net.URL").init( baseURL, theRelativeURL ) /> <cfoutput> <p>theBaseURL = #theBaseURL#</p> <p>theRelativeURL = #theRelativeURL#</p> <p>absURL = #absURL.toString()#</p> </cfoutput>
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.
0 comments:
Post a Comment