Search code examples
jsfurlspecial-charactershtml-escape-characters

How to escape/avoid the ampersand (&) in a JSF url


I use window.open(url,"selectWindow","status=no,width=610,height=480,scrollbars=no") in JSF. The url looks something like this :

/abcxyz.jsf?param1=value1&param2=value2 

which would show in the popup window like :

/abcxyz.jsf?param1=value1&param2=value2

The problem is, the value2 is a string which has an & in it. Say, value2 = ab&12. How can I make sure that the value2 is read as ab&12 and that it doesn't break after ab because of the & symbol?


Solution

  • You need to URL-encode it. In plain Java, that would be

    String encodedValue2 = URLEncoder.encode(value2, "UTF-8");
    

    The & should this way become %26. The charset should be the same as the server is been configured to use to decode the incoming HTTP request URI (which often defaults to ISO-8859-1 though).

    The JSF <f:param> also does that when used in <h:outputLink> and <h:link>, however they aren't helpful in generating URLs for window.open(), so you'd really need to perform this in backing bean with help of URLEncoder or create a custom EL function. If you happen to use the JSF utility library OmniFaces, then you could use #{of:encodeURL()} for that.

    See also: