美文网首页
在SpringBoot上体验一下Servlet4的push

在SpringBoot上体验一下Servlet4的push

作者: KevinBlandy | 来源:发表于2019-02-27 18:16 被阅读0次

    原文地址: https://springboot.io/t/topic/87

    在SpringBoot上体验一下Servlet4的push

    Server Push 其实是http2的一个新特性。servlet4进行了实现。

    关于Server Push

    浏览器在加载一个网页的时候。遇到 css js img 就会再次发起一个http请求去加载资源。所谓的Server Push就是服务器在响应html资源的时候。顺便就把该页面需要的静态资源给 Push 过来了。浏览器不需要再次发起多次http请求。

    pom.xml

    Server Push是http2的东西。在SpringBoot中。使用Undertow开启http2。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
    

    application.properties

    server:
      port: 443
      server-header: springboot.io
      servlet:
        context-path: /
      ssl:
        enabled: true
        key-store: classpath:ssl/localhost.keystore
        key-store-type: PKCS12
        key-store-password: 123456
      # 开启http2
      http2:
        enabled: true
    

    Controller

    @GetMapping
    public Object test(HttpServletRequest request,HttpServletResponse response)throws Exception {
        
        // 通过 Servlet 创建PushBuilder对象,如果不支持,返回null
        PushBuilder pushBuilder = request.newPushBuilder();
        
        // push一个或者多个资源到客户端
        pushBuilder.path("static/css/index.css").push();
        pushBuilder.path("static/bulma/css/bulma.min.css").push();
        
        // 渲染视图
        return new ModelAndView("test/test");
    }
    

    视图

    <!DOCTYPE html>
    <html>
        <head>
            <!-- 需要加载两个静态资源 -->
            <link rel="stylesheet" href="${ctx}/static/bulma/css/bulma.min.css"/>
            <link rel="stylesheet" href="${ctx}/static/css/index.css" />
            <title>Index</title>
        </head>
        <body>
            这是测试页面
        </body>
        <script type="text/javascript">
            
        </script>
    </html>
    
    
    

    通过浏览器查看

    可以看到,html 中加载的两个 css 静态资源,就是通过服务端 push 过来的。

    image.png

    相关文章

      网友评论

          本文标题:在SpringBoot上体验一下Servlet4的push

          本文链接:https://www.haomeiwen.com/subject/lnzfuqtx.html