分享

SpringBoot静态资源文件目录

 码农9527 2021-08-04

SpringBoot在默认的情况下提供了4个静态资源目录: 

/static:classpath:/static/
/public:classpath:/public/
/resources:classpath:/resources/
/META-INF/resources:classpath:/META-INF/resources/1234复制代码类型:[java]

静态资源是指图片,css文件,js文件等。 

classpath

在maven项目中指的

src->main->java或

src->main->resources

下面的目录

static用来存放图片,css文件,js文件等静态文件
public用来存放可以被公开访问的html文件

resources

META-INF/resources

留给程序使用的静态资源目录

 我们还可以自行配置静态资源目录:  

spring:
  resources: static-locations: classpath:/mystatic/123复制代码类型:[java]

spring.resources.static-locations指定了静态资源的位置。一旦自行配置了静态资源目录,系统就会放弃掉默认的静态资源目录,轻易不要自己配置。SpringBoot在默认的情况下提供的4个静态资源目录足够我们使用。  

我们在resources下的public文件下创建index.html,当我们在网页访问根目录时会直接访问到index.html  

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
</head>
<body>
<h1>JavaFamily</h1>
</body>
</html>12345678910复制代码类型:[java]

然后在static文件下创建favicon.ico文件(一张图片),这张图片会自动被SpringBoot设置为图标:  

SpringBoot静态资源文件目录

执行代码,在浏览器访问http://localhost:8888  

SpringBoot静态资源文件目录

如果图标显示不出来,建议刷新浏览器缓存:  

Mac:command+shift+r  

windows:ctrl+F5  

WebJars  

将通用的Web前端资源打包成Java的Jar包,借助Maven工具对其管理,保证这些Web资源版本唯一性,简而言之,WebJars是打包在JAR存档文件中的客户端依赖项。它们适用于大多数JVM容器和Web框架,升级也比较容易。  

为什么要使用WebJars?因为简单!他可以轻松的管理web中的依赖,使用maven就能下载web依赖。还可以对页面依赖的版本进行自动检测,解决了web组件传递依赖的问题和版本问题。  

https://www./一个专门的webjars资源网站,可以在这里寻找自己需要的资源。在自己的项目中添加对应的maven依赖,就可以使用它们了。  

SpringBoot静态资源文件目录

我们将jquery和bootstrap引入pom.xml文件中:  

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.6.0</version>
</dependency>

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>5.0.2</version>
</dependency>1234567891011复制代码类型:[java]

之后编写index.html  

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
 <link rel="stylesheet" href="/webjars/bootstrap/5.0.2/css/bootstrap.min.css">
</head>
<body>
<h1 style="color: red">JavaFamily</h1>
<strong>SUCCESS!</strong>
<script src="/webjars/jquery/3.6.0/jquery.min.js "></script>
<script src="/webjars/bootstrap/5.0.2/js/bootstrap.min.js"></script>
</body>
</html>1234567891011121314复制代码类型:[java]

SpringBoot静态资源文件目录

如果不想添加jquery和bootstrap依赖的版本号,并且使用的是Spring4.2以上的版本。那么可以使用加入webjars-locator组件:  

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>webjars-locator</artifactId>
   <version>0.41</version>
</dependency>12345复制代码类型:[java]

使用组件之后就不需要在写版本号了。  

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
 <link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
</head>
<body>
<h1 style="color: red">JavaFamily</h1>
<strong>SUCCESS!</strong>
<script src="/webjars/jquery/jquery.min.js "></script>
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多