SpringBoot之前端檔案管理
WebJars能使Maven的依賴管理支援OSS的JavaScript庫/CSS庫,比如jQuery、Bootstrap等。 (1)新增js或者css庫 pom.xml
Xml程式碼
<dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7-1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.1</version> </dependency>
src/main/resources/static/demo.html
Html程式碼
<html> <head> <script src="/webjars/jquery/3.1.1/jquery.min.js"></script> <script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script> <title>WebJars Demo</title> <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" /> </head> <body> <div class="container"><br/> <div class="alert alert-success"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> Hello, <strong>WebJars!</strong> </div> </div> </body> </html>
啟動應用後可以看到以下log:
引用
2017-02-09 13:52:48.117 INFO 6188 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
啟動應用訪問 http://localhost:8080/demo.html
(2)省略版本號 很少在程式碼中硬編碼版本號,所以需要隱藏它。 pom.xml新增webjars-locator org.springframework.web.servlet.resource.WebJarsResourceResolver
Java程式碼
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
<version>0.31</version>
</dependency>
src/main/resources/static/demo.html
引用
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
<title>WebJars Demo</title>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
->
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
<title>WebJars Demo</title>
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css" />
啟動應用再次訪問 http://localhost:8080/demo.html 結果和上邊一樣。 引入的開源JavaScript庫/CSS庫將會以jar的形式被打包進工程! spring-boot-demo1-0.0.1-SNAPSHOT.jarBOOT-INFlib
引用
bootstrap-3.3.7-1.jar
└─ META-INF
└─ resources
└─ webjars
└─ bootstrap
└─ 3.3.7-1
├─ css
| ├─ bootstrap.min.css
| ├─ bootstrap.min.css.gz # Gzip檔案
...
引用
jquery-3.1.1.jar
└─ META-INF
└─ resources
└─ webjars
└─ jquery
└─ 3.1.1
├─ jquery.min.js
...