Traditionally, I figure out which page URL has been requested by recreating it from various CGI variables:
<!--- Get requested URL. ---> <cfset strUrl = ( IIF( (CGI.https EQ "On"), DE( "https://" ), DE( "http://" ) ) & CGI.http_host & CGI.script_name & "?" & CGI.query_string ) />
As you can see, it takes into account CGI.https, CGI.http_host, CGI.script_name, and CGI.query_string. This works totally fine for me. But, I have been told that relying on CGI variables is not a good way to go because every server handles CGI data differently. In another blog post, Dan G. Switzer, II made this comment:
Also, custom header information can be applied by custom filters run within the web server--which is why the CGI scope was designed to return an empty string if the key isn't explicitly defined. One reason I don't rely on the cgi.script_name is that not all web servers return it. I really try to avoid using the CGI scope when at all possible.
Frankly, the idea of not using the CGI scope was a bit scary. How could I figure out the URL? Turns out, you can get it directly from the Request servlet object that is available through the ColdFusion page context:
<!--- Get request from ColdFusion page contenxt. ---> <cfset objRequest = GetPageContext().GetRequest() /> <!--- Get requested URL from request object. ---> <cfset strUrl = objRequest.GetRequestUrl().Append( "?" & objRequest.GetQueryString() ).ToString() />
The GetRequestUrl() returns a string buffer which is why the we call ".ToString()" on the GetRequestUrl() return value; this converts the string buffer to a simple string. Before we convert the url buffer to a string, though, we append the query string to it. As you can see, the query string is also available through the request object. That's all there is to it.
Now getting the requested URL is CGI-agnostic. But, how does the request servlet object know what the URL and query string values are? Frankly, that's not my concern. That's the whole beauty behind black-boxing data retrieval - I don't need to know the implementation of it, I just need to know that it returns the correct values.
Want to use code from this post? Check out the license.