Register a custom WebSocketCreator in your WebSocketServlet.configure()
method.
Skip the ServletContext entirely.
Just pass in the HttpClient into your custom creator.
public class MyCreator implements WebSocketCreator
{
private HttpClient client;
public MyCreator(HttpClient client)
{
this.client = client;
}
@Override
public Object createWebSocket(ServletUpgradeRequest
servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse)
{
return new MyEndpoint(client);
}
}
public class MyWebSocketServlet extends WebSocketServlet
{
private HttpClient httpClient;
@Override
public void init() throws ServletException
{
httpClient = new HttpClient();
try
{
httpClient.start();
}
catch (Exception e)
{
throw new ServletException("Unable to start HttpClient", e);
}
}
@Override
public void destroy()
{
try
{
httpClient.stop();
}
catch (Exception e)
{
throw new RuntimeException("Unable to stop HttpClient", e);
}
}
@Override
public void configure(WebSocketServletFactory
webSocketServletFactory)
{
webSocketServletFactory.setCreator(new MyCreator(httpClient));
}
}
Joakim Erdfelt / [email protected]
On Thu, Jul 13, 2017 at 1:17 AM, Alexander Farber <
[email protected]> wrote:
> Good morning,
>
> In a custom WebSocketServlet I create, start and store in the
> ServletContext a Jetty HttpClient instance:
>
> public class MyServlet extends WebSocketServlet {
> private final SslContextFactory mSslFactory = new SslContextFactory();
> private final HttpClient mHttpClient = new HttpClient(mSslFactory);
>
> @Override
> public void init() throws ServletException {
> super.init();
>
> try {
> mHttpClient.start();
> } catch (Exception ex) {
> throw new ServletException(ex);
> }
>
> ServletContext ctx = getServletContext();
> ctx.setAttribute("http_client", mHttpClient);
> }
>
> And then in the onWebSocketText method of my custom WebSocketListener I
> need to retrieve the running HttpClient instance.
>
> I have provided few more details at:
> https://stackoverflow.com/questions/45074546/how-to-
> access-servletcontext-from-jetty-websocketlistener
>
> How to get ahold of the ServletContext please? Should I create a custom
> WebSocketCreator for that?
>
> Regards
> Alex
>
>
>
>
> _______________________________________________
> jetty-users mailing list
> [email protected]
> To change your delivery options, retrieve your password, or unsubscribe
> from this list, visit
> https://dev.eclipse.org/mailman/listinfo/jetty-users
>
_______________________________________________
jetty-users mailing list
[email protected]
To change your delivery options, retrieve your password, or unsubscribe from
this list, visit
https://dev.eclipse.org/mailman/listinfo/jetty-users