jsfweb.xmlfaceletsurl-pattern

Sometimes I see JSF URL is *.jsf, sometimes *.xhtml and sometimes /faces/*. Why?


Been try to learn JSF, and sometimes I see the URL is *.jsf and sometimes is *.xhtml or /faces/*. Can someone fill my knowledge, please? When I create a JSF using Facelet, the file extension is .xhtml, so where does .jsf URL extension come from?


Solution

  • The .jsf extension is where the FacesServlet is during the JSF 1.2 period often mapped on in the web.xml.

    <servlet-mapping>
        <servlet-name>facesServlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    

    The .xhtml extension is of the actual Facelets file as you've physically placed in the webcontent of your webapp, e.g. src/main/webapp/page.xhtml.

    If you invoke this page with the .jsf extension, e.g. http://localhost:8080/contextpath/page.jsf then the FacesServlet will be invoked, locate the page.xhtml file and parse/render its JSF components. If the FacesServlet isn't invoked, then the enduser would end up getting the raw XHTML source code (which can be seen by rightclick, View Source).

    Sometimes a *.faces extension or /faces/* foldermapping is been used. But this was from back in the JSF 1.0/1.1 ages. You're free to choose and use whatever mapping you'd like to let FacesServlet listen on, even if it's a nothing-saying *.xyz. The actual page itself should always have the .xhtml extension, but this is configureable by the following <context-param> in web.xml:

    <context-param>
        <param-name>jakarta.faces.DEFAULT_SUFFIX</param-name> <!-- or javax if you're still on JSF 2.x or older -->
        <param-value>.xml</param-value>
    </context-param>
    

    This will change the FacesServlet to locate page.xml instad of (default) page.xhtml.

    Since JSF 2.0 a *.xhtml mapping is been used. In JSF 1.x it was not possible to use the same mapping extension as the physical file. It would result in an infinite loop. But since JSF 2.0 it is possible and this allows you to call the page by http://localhost:8080/contextpath/page.xhtml without any ambiguity.

    <servlet-mapping>
        <servlet-name>facesServlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    

    This way you don't need to configure some security restrictions to hide the raw source files away for cases whenever the enduser changes for example .jsf in URL to .xhtml in browser address bar. As per JSF 2.3, the FacesServlet will by default be autoregistered on *.xhtml too (next to /faces/*, *.faces and *.jsf). This is backported to Mojarra 2.2.11.

    See also: