Spring Boot 入门 - 基础篇(5)- 使用WebJars

WebJars能使Maven的依赖管理支持OSS的JavaScript库/CSS库,比如jQuery、Bootstrap等。

[b](1)添加js或者css库[/b]
pom.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>
<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:
[quote]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][/quote]

启动应用访问 http://localhost:8080/demo.html
[img]http://dl2.iteye.com/upload/attachment/0122/9682/3e52e61f-a0aa-33de-bb86-62acafd05236.png[/img]

[b](2)省略版本号[/b]

很少在代码中硬编码版本号,所以需要隐藏它。

pom.xml添加webjars-locator
org.springframework.web.servlet.resource.WebJarsResourceResolver
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
<version>0.31</version>
</dependency>


src/main/resources/static/demo.html
[quote]<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" />[/quote]

启动应用再次访问 http://localhost:8080/demo.html 结果和上边一样。

[color=blue]引入的开源JavaScript库/CSS库将会以jar的形式被打包进工程![/color]
spring-boot-demo1-0.0.1-SNAPSHOT.jar\BOOT-INF\lib
[quote]bootstrap-3.3.7-1.jar
└─ META-INF
└─ resources
└─ webjars
└─ bootstrap
└─ 3.3.7-1
├─ css
| ├─ bootstrap.min.css
| ├─ bootstrap.min.css.gz # Gzip文件
...[/quote]

[quote]jquery-3.1.1.jar
└─ META-INF
└─ resources
└─ webjars
└─ jquery
└─ 3.1.1
├─ jquery.min.js
...[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值