Wednesday, May 16, 2007

HTML/JSP: How to pass the '#' character as an HTML request parameter

I found myself into a situation today, where I was trying to pass a string (actually a URI) as a request parameter through a URL, but my program wouldn't work. I added debug print statements and found out that although I was passing the string
the page that was processing the request only received
It immediately became apparent that the problem was caused by the hash/pound symbol ('#'), which is used as a special character in URLs to introduce a "fragment identifier". A URL link containing a fragment identifier links to a specific section of a webpage and a browser that follows this link will set its viewport on this exact section rather than the top of the page. Escaping this character is rather easy: you just need to replace '#' with '%23'. In my case I was using JSP with JSTL, and this string was returned as a bean property (for those who are curious it is the URI for an OWL ontology resource). This substitution can be performed by using the fn:replace function:
<a href="${fn:replace(original_string,'#','%23')}">Text here</a>
I noticed that it is not necessary to "decode" the '%23' escaped character back to '#' on the request-handler side, but I am not sure if this is specific to JSP only.
Of course, in order for all this to work, you need to import the fn tag library.
<%@ taglib prefix="fn" uri="" %>

No comments: