Spring Boot中使用WebJars

1、WbeJars介绍
WebJars是将Web前端JQuery和Bootstrap等资源打包成Java的Jar包,这样在Java Web开发中我们可以借助Maven这些依赖库的管理。
项目中需要的JQuery和Bootstrap的Maven依赖可以去WebJars官网下载。
2、Spring Boot使用WebJars的原理
在前面文章Spring Boot自动配置原理的时候讲过。
xxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxProperties:配置类来封装配置文件的内容;
我们来看看WebMvcAuotConfiguration,这是Spring boot为我们自动配置的Web开发组件。

public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!registry.hasMappingForPattern("/webjars/**")) {
	customizeResourceHandlerRegistration(registry
			.addResourceHandler("/webjars/**")
			.addResourceLocations("classpath:/META-INF/resources/webjars/")
			.setCachePeriod(getSeconds(cachePeriod))
			.setCacheControl(cacheControl));
	}

可以看到,所有/webjars/**都可以去classpath:/META-INF/resources/webjars/下找资源。知道原理之后,我们在项目中引入Jquery和Bootstarp的Maven依赖。
3、引入依赖

<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.3.1-1</version>
</dependency>
<dependency>
     <groupId>org.webjars</groupId>
     <artifactId>bootstrap</artifactId>
     <version>4.1.3</version>
 </dependency>

引入依赖的结构
在这里插入图片描述
4、在我们的项目中引入Bootstrap

<link th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.css}" rel="stylesheet">

猜你喜欢

转载自blog.csdn.net/qq_27046951/article/details/82768027