In this article, I will demonstrate how to retrieve page properties using the PageContext object, which is available in ColdFusion and Lucee. This is a much more modern and efficient method than using CGI variables, which are often unreliable. 

There are a few articles on how to use the PageContext Java object to derive the page URL; however, this article takes it a step further, showing you a complete example of how to retrieve the port and script name, if they are present, in the URL.


Using CGI Variables for the Page Properties May Be Unreliable


CGI, or Common Gateway Interface, is an old standard that is slow and unreliable. CGI is an outdated standard that requires a separate process for each variable, and these processes can consume a significant amount of server resources. Since CGI is an outdated standard, it can be programmed with any language, is prone to various attacks, and may not always work reliably, especially when proxy servers handle networking traffic. While the security issues are low, it is best to use modern alternatives to CGI, such as HttpHeaders, or, in this case, using the PageContext Java object, which is already instantiated when using ColdFusion or Lucee. 


What is the PageContext Object?


The getPageContext() method is a multi-threaded Java Server Pages (JSP) and ColdFusion function that retrieves the request and response objects, including paths, headers, and form data. Examples of methods for this include getRequest()getResponse()getSession(), etc. In this example, we are using the getRequest() method to obtain the server name, port, and the variables found in the URL.


A Modern ColdFusion and Lucee Function to Retrieve the Page URL


<cffunction name="getPageUrl" returntype="string" output="false">
	<cfargument name="includePort" required="false" default="false" type="boolean" />

	<!--- Get request object from the jsp pageContext object --->
	<cfset PageRequestObj = getPageContext().getRequest()>
	<!--- Get the URL. This does not include the port or the query string --->
	<cfset pageUrl = PageRequestObj.getRequestURL().toString()>
	<cfset pageQueryString = PageRequestObj.getQueryString()>

	<!--- Build the URL string --->
	<cfif arguments.includePort>
		<cfset pagePort = PageRequestObj.getServerPort()>
		<cfset pageUrl = pageUrl & ':' & pagePort>
	</cfif>
	<!--- Note: the pageQueryString may be undefined when there is an index.cfm. This may throw an error if I don't use an isDefined --->
	<cfif isDefined("pageQueryString") and len(pageQueryString)>
		<cfset pageUrl = pageUrl & '?' & pageQueryString>
	</cfif>

	<!--- Return it --->
	<cfreturn pageUrl>

</cffunction>

Further Reading