I have a Spring-MVC application with Freemarker as the view component.
In my templates, several links are generated which point back to my application and which include URL parameters containing a hash key (#).
Example:
parameter: Q#106368 11
URL generated by Freemarker with encoded param: testurl.html?key=Q%23106368%2011
I use JavaScript to redirect to this URL (reason: I use JS to manage loading of 2 frames at the same time).
The redirect method is simple:
function redir(url) {
window.location.href = url;
}
The JS call generated by Freemarker looks like
<a href="javascript:redir('http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011');">test</a>
My problem is that the browser / Javascript converts back the URL encoded parameter, thinks there is a # and cuts off there.
When I use window.location.href='http://...' directly it works. Only when using the method parameter it seems to be magically URL decoded and then the redirect fails because the URL gets cut off at the #.
Is there an easy way to transmit the parameter correctly?
I am aware that I could replace the #, e.g. with $$$hash$$$, in the template and do the replacement on the server side again. But there are so many places I would have to change…
As Marc B commented, it is necessary to URL encode again. The method would be
encodeURI(). However, this method does not encode the#sign. For my specific use case, I have to replace the#sign with%23after the encoding.The redirect JS method finally looks like:
Comparing escape(), encodeURI(), and encodeURIComponent()