Search code examples
javarestjax-rscxfweb.xml

How can I serve static content from CXF / JAX-RS with my rest API mapped to root context?


I have a rest API using CXF to implement JAX-RS where the REST endpoints are directly on the root context.

For example if my root context is localhost:8080/myservice

And my endpoints are:
localhost:8080/myservice/resource1
localhost:8080/myservice/resource2

But I want to serve static content like this:
localhost:8080/myservice/docs/swagger.json

In my web.xml I'd like to do something like this:

<servlet-mapping>
  <servlet-name>CXFServlet</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>/docs/*</url-pattern>
</servlet-mapping>

But that doesn't work, the CXFServlet picks up all requests and I could not find a way to configure CXF / JAX-RS to serve my static content without including new libraries and creating byte streams, etc. which I don't want to do. I want to just map to the default servlet.

The CXF documentation is not easy to follow, and I tried unsuccessfully to do the following:

<servlet>
  <servlet-name>CXFServlet</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <init-param>
    <param-name>static-resources-list</param-name>
    <param-value>
      /docs/(\S)+\.html
      /docs/(\S)+\.json
    </param-value>
  </init-param>
</servlet>

Any ideas?


Solution

  • I found the solution thanks to this link!

    Below is my servlet config in my web.xml to serve static resources with a CXFServlet that is mapped to root.

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <init-param>
            <param-name>redirects-list</param-name>
            <param-value>
              /docs/(\S)+\.html
              /docs/(\S)+\.json
        </param-value>
        </init-param>
        <init-param>
            <param-name>redirect-attributes</param-name>
            <param-value>
              javax.servlet.include.request_uri
        </param-value>
        </init-param>
        <init-param>
            <param-name>redirect-servlet-name</param-name>
            <param-value>default</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    

    Hope this helps someone else.