Search code examples
javajsfservletsjsf-2

JSF 2.0 and custom path in @WebServlet


I have a JSF webapp with some standard JSF pages and backing beans.
I am trying to use the urlPatterns parameter of the @WebServlet annotation to get my app pages served from a non-root path. Ex:

http://localhost/<appName>/<myPath>/index.xhtml  

where myPath = /web as shown in the code below.

This doesn't seem to work. The application only response to requests made to:

http://localhost/<appName>/index.xhtml

The application is deployed in Tomcat 7.0. And the following JSF dependencies:

<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.1.16</version>
</dependency>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1.16</version>
</dependency>

Any ideas?

import javax.faces.webapp.FacesServlet;

@WebServlet(urlPatterns = "/web",
            initParams = { @WebInitParam(name = "javax.faces.PROJECT_STAGE",
                           value = "Development") })
public class AppServlet implements Servlet {

    FacesServlet servlet = new FacesServlet();

    @Override
    public void destroy() {
        servlet.destroy();
    }

    @Override
    public ServletConfig getServletConfig() {
        return servlet.getServletConfig();
    }

    @Override
    public String getServletInfo() {
        return servlet.getServletInfo();
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        servlet.init(servletConfig);
    }

    @Override
    public void service(ServletRequest req, ServletResponse resp)
            throws ServletException, IOException {
        servlet.service(req, resp);
    }
}

Solution

  • The URL pattern of /web matches only and only the http://localhost/<appName>/web folder and not the subfolders and files like http://localhost/<appName>/web/index.xhtml as you seemed to expect. For that, you should use an URL pattern of /web/*.

    @WebServlet("/web/*")
    

    Unrelated to the concrete problem, this won't work together with JSF as its own FacesServlet would not be invoked this way. Perhaps you actually need a servlet filter? Also, that web init parameter creates a <servlet><init-param> and not a <context-param> as usually required for JSF. Just in case you didn't knew that.