In case you ever need to host static content from CXF, try this before jumping off a bridge

For some odd reason, you may find that you really, really want to host some static content on your CXF server. Maybe you want to do something like host Swagger or IO Docs side by side with your REST API and you don’t feel like setting up a whole new service.

And if you’re like me, you’ve already shot yourself in the foot because you bound your RESTful service to the root of your Tomcat webapp. For example, your CXF servlet is bound to http://localhost:8080/petsore/* but you now want http://localhost:8080/petstore/docs/ to host your documentation, and CXF thinks your docs are an API endpoint.

You made your life complicated and set it up like this too, didn’t you?

And maybe you’ve tried to read the impenetrable documentation on the Apache CXF site with its maddening language about servlet initialization params relating to “redirects.” I debugged deep into the CXF sourcecode to figure what’s really going on. You need to start with CXF’s AbstractHTTPServlet.java.

Now that I’ve said all that, let me get to the bottom line. All you really need to do is make sure you’ve added two initialization params to your web.xml:

In my configuration, I had the Swagger docs under the src/main/webapps folder in my Maven project, so your mileage may vary depending on your configuration.

Good luck out there.

3 thoughts on “In case you ever need to host static content from CXF, try this before jumping off a bridge”

  1. Your above solution didn’t work for me, but this did:

    CXFServlet
    org.apache.cxf.transport.servlet.CXFServlet

    redirects-list

    /docs/(\S)+\.html
    /docs/(\S)+\.json

    redirect-attributes

    javax.servlet.include.request_uri

    redirect-servlet-name
    default

    1

    CXFServlet
    /*

  2. Your above solution didn’t work for me but this did:

    <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>

Leave a Reply

Your email address will not be published. Required fields are marked *