websocket icon indicating copy to clipboard operation
websocket copied to clipboard

server: HandshakeRequest: add getServletContext()

Open morgwai opened this issue 2 years ago • 7 comments

Currently there is no easy universal way to obtain reference to the ServletContext from ServerEndpointConfig.Configurator's level if the websocket container is running as a part of a Java Servlet app. This may be useful to access app init params or app wide attributes. As of 2.1.1 the standard practice is to obtain ServletContext ref via HttpSession in modifyHandshake(...):

public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
	final var httpSession = request.getHttpSession();
	if (httpSession != null) {
		final var servletCtx = ((HttpSession) httpSession).getServletContext();
		// use servletCtx to obtain params, attributes and put them into userProperties
	} else {
		// give up or perform some really ugly hacks...
	}
}

This however requires to enforce creating of session for each handshake request to Endpoints using such Configurator (with Filters or Listeners). This in turn, may not always be acceptable due to various reasons (cookies disabled, user explicitly refusing any data storage etc) and may not serve any other purpose than this server-internal workaround.
Other workarounds include really ugly hacks such as storing a ref to ServletContext on a static var...

Adding getServletContext() removes necessity for any such hacks. This should also be very easy to implement by existing websocket server containers, for example here is an example 6 line patch for Jetty.

Please forgive me, as I'm not sure if just posting a pull-request here is the right way to get something included in this API: if I receive positive initial feedback regarding this, I will get myself familiar with the process and will perform other necessary steps.

Thanks!

morgwai avatar Aug 19 '23 17:08 morgwai

An alternative to this PR could be adding a method like Object getWrappedHttpServletRequest() in case it turns there are other usecases that need yet another data obtainable from HttpServletRequest...

morgwai avatar Aug 19 '23 23:08 morgwai