Fixing &’s in the URL with getPageContext().forward()

This is a bug that I've been getting on here for a while, and I've been meaning to fix it. Strangely enough today is the day!

The issue comes when either an older browser, or a badly implemented RSS reader picks up my links.

Since both my webpage is and my RSS feed is XML (XHTML), I will turn a link that looks like /?action=displayPost&ID=99 into one that looks like /?action=displayPost&ID=25, as '&' is not a valid XML element.

This is normally no issue, but sometimes I do get requests that still retain the & within the URL, as it hasn't been translated back to the normal ampersand.

My original thought was to fix the issue with a <cflocation>, however I didn't feel that would be seamless enough, and if there was form data going through, that wouldn't work either.

So I used getPageContext().forward() to forward on the request, after I fixed it by replacing all '&amp;' with '&' in the url query string, and because the forward() method simply pushes the java HttpServletRequest and HttpServletResponse objects through to the new request, everything is totally seamless. Form data gets passed through, and the user won't even see a URL change in their browser.

Here is the code below – I have it in a custom tag called 'fixAmp.cfm' that gets called in my Application.cfm

<cfparam name="request.fixAmp" type="boolean" default="false">

<cfif (NOT request.fixAmp) AND (findNoCase("&amp;", cgi.query_string ) gt 0)>

request.fixAmp = true;
queryString = replace(cgi.query_string, "&amp;", "&", "all");
getPageContext().forward(cgi.script_Name & "?" & queryString);



//just for cleanup
StructDelete(request, "fixAmp");


The reason I have the request.fixAmp flag in there is because on some servers, if you forward the request, the CGI data will stay the same. Hence the tag will go into a infinite loop as it never think's it's fixed the ampersand.

And presto, you never have to worry about issues with useing &amp; in your links again!


Leave a Comment


  • John | July 24, 2004

    You could just use:

    (findNoCase("&amp;", cgi.query_string))

    insted of using "gt 0"

    Good post by the way!

  • zaheer | August 3, 2005


  • Philippe | March 31, 2007

    Do you know if there’s a CF5 version of this script because I’m think getPageContext is not valid on this kind of server.

  • paul | April 16, 2007

    how are you calling this from within application.cfm?

  • Henry K | April 2, 2008

    Awesome, this just saved me a huge headache.

  • shane | June 2, 2009

    Thanks for this solution. It also works for remote calls to CFC methods…

  • sam | September 21, 2010

    thanks for this tip you + Carehart’s post is going to make me look like a genius tomorrow!