Spring Boot + WebJars 整合運用

Spring Boot + WebJars 整合運用

示例:SpringBoot | 第十八章:web應用開發之WebJars使用

WebJars介紹及使用

WebJars是一個很神奇的東西,可讓你們以jar包的形式來使用前端的各類框架、組件。

#### 什麼是WebJarscss

WebJars是將客戶端(瀏覽器)資源(JavaScript,Css等)打成jar包文件,以對資源進行統一依賴管理。WebJars的jar包部署在Maven中央倉庫上

#### 爲何使用前端

咱們在開發Java web項目的時候會使用像Maven,Gradle等構建工具以實現對jar包版本依賴管理,以及項目的自動化管理,可是對於JavaScript,Css等前端資源包,咱們只能採用拷貝到webapp下的方式,這樣作就沒法對這些資源進行依賴管理。那麼WebJars就提供給咱們這些前端資源的jar包形勢,咱們就能夠進行依賴管理。

#### 原理jquery

本來咱們在進行web開發時,通常上都是講靜態資源文件放置在webapp目錄下,在SpringBoot裏面,通常是將資源文件放置在src/main/resources/static目錄下。而在Servlet3中,容許咱們直接訪問WEB-INF/lib下的jar包中的/META-INF/resources目錄資源,即WEB-INF/lib/{*.jar}/META-INF/resources下的資源能夠直接訪問,WebJars也是利用了此功能,將全部前端的靜態文件打包成一個jar包,這樣對於引用放而言,和普通的jar引入是同樣的,還能很好的對前端靜態資源進行管理。

如何使用

1. Maven依賴
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.3.7</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>  


<!-- Package as an executable jar/war -->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <addResources>true</addResources>
    </configuration>
</plugin>
2. 界面引用
<!--若是未引入webjars-locator,相關靜態資源須要版本號,此處不便於升級-->
<script th:src="@{/webjars/jquery/3.3.1/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}"/>
3. 省略頁面引用時的版本號
寫死版本號不利於項目資源升級,可額外使用webjars-locator來省略引用時的版本號:
添加以後的pom文件以下:
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.34</version>
</dependency>
而後就能夠不帶版本號訪問了:
<!--由於額外引入了webjars-locator,因此相關靜態資源的引入可省略版本號便於升級-->
<script th:src="@{/webjars/jquery/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"/>

完整示例

靜態文件工程

相關文章
相關標籤/搜索