How to do server push with standalone Jetty

时光怂恿深爱的人放手 提交于 2019-12-02 08:31:06

Too many questions and it's not really clear what you want to do :)

Jetty exposes a Jetty-specific API on the server to perform pushes (eventually, these APIs will be part of Servlet 4.0).

You can access this API using org.eclipse.jetty.server.Request.getPushBuilder(), see http://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/server/PushBuilder.html

The PushBuilder APIs will then allow you to setup a resource to push, and to push it.

PushCacheFilter implements a cache of correlated resources. When a primary resource that has correlated secondary resources is being requested, PushCacheFilter pushes those correlated resources using the PushBuilder APIs.

If PushCacheFilter does not fit your needs, you can write your own filter with your own logic and perform pushes using the PushBuilder APIs.

On the client side, if you want to use Java APIs to perform requests and receive pushes, you have to use HTTP2Client, see http://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/http2/client/HTTP2Client.html.

You can find examples of how to perform a request and receive pushes here.

If you want a full fledged example similar to yours (index.html + bunch of images), you can look at the HTTP/2 demo.

UPDATE: Simple example of how to use PushBuilder.

public class MyPushFilter implements Filter {
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String uri = httpRequest.getRequestURI();
        switch (uri) {
            case "/index.html":
                // Jetty specific APIs for now.
                PushBuilder pushBuilder = Request.getBaseRequest(request).getPushBuilder();
                pushBuilder.path("/styles.css").push();
                pushBuilder.path("/background.png").push();
                break;
            default:
                break;
        }
        chain.doFilter(req, resp);
    }
}

The example above is very very simple. It does not handle HTTP version, conditional headers, etc. Please have a look at the implementation of PushCacheFilter here for a better implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!