Search code examples
jsf-2character-encodingurl-encodingmojarra

JSF2 h:outputLink won't encode properly


Using Mojarra 2.1.7

Code

<h:outputLink value="index.jsf">Login page
    <f:param name="test" value="! åöä"></f:param>
</h:outputLink>

output: index.jsf?test=%21+åöä

Some characters got escaped but others didn't. Obviously very hard to handle.

Why is this and does anyone know a good way to manage this?

http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder.html

Seems to be used since it parses space with +.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

Thankful for answers


Solution

  • Aren't you confusing the JSF-generated HTML code with whatever you see in the browser's status or address bar? Surely it's already fully URL-encoded in the generated HTML code. I just did a quick test and according to View Source in browser it has generated (assuming that you haven't changed the JSF2/Facelets default response encoding of UTF-8) the following piece of HTML:

    <a href="index.jsf?test=%21+%C3%A5%C3%B6%C3%A4">Login page</a>
    

    But indeed, Chrome and Firefox shows index.jsf?test=%21+åöä in the browser's status bar when you hover the link and also in the address bar when you click the link. That's just a browser-specific feature, which is a completely different matter.

    I'm not sure what your concrete problem is as you didn't tell anything about it, but the way you put the question gives me the impression that the request URL isn't properly URL-decoded by the servletcontainer in question and thus you received mojibake while accessing the request parameter.

    As you might have guessed now, this has to be solved in the servletcontainer's side. It's also unclear which one you're using, so here are some examples for Tomcat and Glassfish:

    • In Tomcat you need to set the URIEncoding attribute of the <Connector> element in Tomcat's server.xml to UTF-8.

      <Connector ... URIEncoding="UTF-8">
      
    • In Glassfish you need to add <parameter-encoding> to /WEB-INF/glassfish-web.xml:

      <parameter-encoding default-charset="UTF-8" />
      

    As to the "parsing" (actually, "encoding" is the right term) the space with +, I'm not sure why you pointed out that, but that's simply how spaces in URL query strings are supposed to be encoded. I think that you expected it to be %20, but that is only how spaces in hierarchial part of the URL (the part before the query string, which is separated by ?) is supposed to be encoded.