1

When using JSF, one can choose from several extensions like:

  1. /faces/*
  2. *.jsf
  3. *.xhtml

Where the last one is recommended for JSF 2.2 at least. But what if I wanted to use the .jsf extension, I get a problem here is that if someone were to type out of "curiosity" .xhtml then weird stuff could start to happen if you for example mix JSF tags with normal HTML tags.

So I know that GlassFish server's Admin Console for example forces the URL rewrite to .jsf if I type .xhtml, how can I do this ?

Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44

1 Answers1

2

Two ways:

  1. Simply restrict direct access to .xhtml files in web.xml.

    <security-constraint>
        <display-name>Restrict direct access to XHTML files</display-name>
        <web-resource-collection>
            <web-resource-name>XHTML files</web-resource-name>
            <url-pattern>*.xhtml</url-pattern>
        </web-resource-collection>
        <auth-constraint />
    </security-constraint> 
    

    See also JSF returns blank/unparsed page with plain/raw XHTML/XML/EL source instead of rendered HTML output.

  2. Create a servlet filter which listens on *.xhtml and redirects to *.jsf.

    @WebFilter("*.xhtml")
    public class FacesUrlRewriteFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            String redirectURI = request.getRequestURI().replaceAll("xhtml$", "jsf");
            String queryString = request.getQueryString();
    
            if (queryString != null) {
                redirectURI += "?" + queryString;
            }
    
            response.sendRedirect(redirectURI);
        }
    
        // ...
    }
    

    See also How to use a servlet filter in Java to change an incoming servlet request url?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555