在开发的过程中,很多时候需要结合前端进行开发。本节将介绍Spring Boot框架整合WebJars进行前端静态JavaScript和CSS。
作为开发者,对Bootstrap和jQuery应该不会陌生。接下来我们将在Spring Boot项目中引入WebJars,对应二者的JAR进行使用,在pom文件中加入二者的依赖文件,如代码
<!--引入bootstrap-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<!-- 引用jquery -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
其实到这里整合完毕了,但是为了证实我们是否可以成功引用,在src/main/recources/static文件夹下新建index.html,在HTML中引入刚刚加入依赖的文件。index.html页面代码如代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css">
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br>
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
hello,<strong>bootstrap and jquery</strong>
</div>
</div>
<script type="text/javascript">
alert($('.close').attr('href'));
</script>
</body>
</html>
配置
server.port=8089
在HTML页面中,我们分别对Bootstrap和jQuery进行了引用,使用Bootstrap对a标签进行了样式的修饰,使用jQuery在打开页面时利用告警输出了a标签的href值。启动项目,让我们来证实一下,在浏览器上访问http://localhost:8089,可以看到之前的操作都实现了。
其实WebJars还提供了很多其他的依赖,具体使用可以查看WebJars官网(官网地址:https://www.webjars.org/)。