I've looked at trying to get the ServletContext from the class loader and while the container has that mapping internally it is not currently exposed. I'd have to make some changes to Tomcat to enable the WebSocket to get to it and I'm not overly keen on that.
I think there are three options:
1. Do something container specific to find the ServletContext.
2. ServerContainer.setContext(Object ctxt)
3. ServerContainerProvider.getServerContainer(Object ctxt)
I don't like 1 for several reasons. Primarily because it is container specific and it would make a container neutral WebSocket implementation impossible. I know container neutrality isn't currently a formal requirement but at the moment there is nothing that requires a container specific approach. I would very much prefer to keep it that way.
Tomcat currently uses 2. On the plus side this method only needs to be called in a 100% programmatic case as the SCI can call it in all other cases. That keeps things simple for the developer and the implementation can throw an exception if it isn't set in the 100% programmatic case. The downside is that it still relies on the current class loader to map to the correct ServletContext. That is potentially fragile since the current class loader may not be the web application class loader in all cases. There are likely to be ways around this but it adds some complexity. The other advantage of 2 is that it can easily be added to the API at a later date if we don't add it now.
Option 3 has the advantage of not needing to use the class loader to map to the ServletContext but the price is that every call must provide a ServletContext. That may cause complications in some use cases if the ServletContext isn't easily available. The other downside is that adding this to the spec later would mean (potentially) deprecating the current method and adding this new one.
My preference is for 2 or 3 with perhaps a slight leaning towards 2.