Search code examples
embedded-jettyjetty-9

Embedded Jetty 9 - I need Websocket Server, REST Servlet, and File Server


Is it possible to have all 3 (Websocket, REST Servlet, and a File server) all on the same port?

I've been going through the web finding lots of examples of partial solutions, but the Jetty setup has so many variations that it's hard to determine what will work for me.

I'd prefer to use JSR-356 websocket api rather than the Jetty proprietary, in case I have to move to a different server later.


Solution

  • Yes, and it easiest if the HTTP paths are different.

    • WebSocket on /ws/*
    • REST on /api/*
    • Static File Serving on /static/* (or just on /, which means for all requests that don't start with /ws/ or /api/)

    But if you don't want to use paths, then you have to use some other separator of the requests.

    • WebSocket upgrade is a GET with a Connection: upgrade so that won't conflict with either the REST or file serving.
    • REST can easily conflict with file serving if the paths overlap. (if the client asks for /stuff/here and you have REST setup on /* then what does that request mean? REST or static files?)
    • File serving is traditionally handled by the servlet spec default url-pattern of /, which means if no other url-pattern has been designated to handle the requested HTTP path, then static files are served.

    This is advice:

    • Don't overlap your url-patterns.
    • Use separate paths for each. (you'll thank yourself later)
    • Don't make REST serve static files (this is super inefficient and a hack at best).