Spring/SpringBoot 使用webjars及启用后端

2021-08-05  本文已影响0人  JohnYuCN

webjars可以使我们可以使用maven和gradle对前端的库进行管理(当然这可能会导致前后端分离的并不纯粹);而前端库的压缩协商,对于提高前端的运行效率至关重要,而这又需要后端的支持,本文也对此内容做了介绍。


2018年8月27日18点:贝加尔湖

原理:

1. webjars 原理:

本质上是让DispatcherServlet可以映射到ar包中META-INF中的静态资源。

2. 压缩文件传送:

本质上是根据前端请求头中的信息:Accept-Encoding: gzip, deflate, br, 为映射到的静态资源寻找.gz或.br压缩资源,如果有则优先返回。如用.css.gz代替.css文件,而浏览器则将其接收后再进行解压缩处理。

案例讲解:

  1. 以引入bootstrap为例,首先在pom中加入bootstrap的webjars:
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.4.1</version>
        </dependency>
  1. 进行静态资源的映射:
@Configuration
@EnableWebMvc
public class WebConf implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/")
                .resourceChain(false);//关闭缓存,有利有调试,生产环境需要设置为true
    }
...

此时可以webjars中的资源进行访问:http://localhost:8080/spd1/webjars/bootstrap/3.4.1/css/bootstrap.css,但些时获取的是原始文件(注意:需要使用网页调度工具才能看到):

image.png
  1. 加入EncodedResourceResolver,它包含了gzip和br压缩的协商
@Configuration
@EnableWebMvc
public class WebConf implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/")
                .resourceChain(false)//关闭缓存,有利有调试,生产环境需要设置为true
                .addResolver(new EncodedResourceResolver());
    }

此时,可以看到文件体积从146kB降到了21.5KB:


image.png
上一篇下一篇

猜你喜欢

热点阅读