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.
No comments:
Post a Comment