在SpringBoot上体验一下Servlet4的push

原文地址: 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容