首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >SpringBoot2.x基础篇:将静态资源打包为WebJars

SpringBoot2.x基础篇:将静态资源打包为WebJars

作者头像
恒宇少年
发布于 2020-04-24 02:33:16
发布于 2020-04-24 02:33:16
68100
代码可运行
举报
运行总次数:0
代码可运行

知识改变命运,撸码使我快乐,2020继续游走在开源界 点赞再看,养成习惯 给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案

概述

我们在编写前后分离项目时,前端的项目一般需要静态资源(ImageCSSJavaScript...)来进行渲染界面,而如果我们对外采用依赖的方式提供使用时,我们的静态资源文件也应该放入打包文件内,这样才能更便捷的提供我们的功能,在我的开源分布式日志框架 minbox-logging 内提供了管理界面的功能,就是采用的这种方式实现,将静态资源以及编译后HTML页面存放到minbox-logging-admin-ui依赖内,下面我们来看下具体的实现方式。

推荐阅读

了解Resources Static Locations

在我们打包静态资源前,首先来了解下SpringBoot提供的spring.resources.static-locations配置默认值,该配置用于配置ResourceHandler,项目启动后会将该参数的配置值列表作为直接可访问的静态目录进行映射,通过这种方式我们就可以直接访问到我们需要的静态资源内容。

spring.resources.static-locations配置位于org.springframework.boot.autoconfigure.web.ResourceProperties配置类内,其默认值是使用本类内的静态常量CLASSPATH_RESOURCE_LOCATIONS的值,如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
                                                              "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

/**
     * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
     * /resources/, /static/, /public/].
     */
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

通过查看源码我们得知,classpath:/META-INF/resources/目录下的资源是可以直接通过默认的映射绑定关系访问到的,通过这一点,我们可以将静态资源依赖内的资源文件存放到META-INF/resources目录下。

资源打包

我们使用Maven方式构建一个普通的项目,在pom.xml文件内添加资源目录配置,在编译过程中将src/main/resources目录下的文件全部复制到META-INF/resources下,如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <targetPath>META-INF/resources</targetPath>
    </resource>
  </resources>
</build>

为了验证资源访问,我们在src/main/resources目录下存放一个名为head.jpg的图片。

我们为了本地演示使用,将Maven项目通过mvn install命令安装到本地仓库,以便于提供给其他项目使用。

使用WebJars依赖

我们来创建一个SpringBoot项目,在项目的pom.xml文件内添加如下依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependencies>
  <!--静态资源的访问映射绑定需要web依赖-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.example</groupId>
    <artifactId>webjars-sample</artifactId>
    <version>1.0-SNAPSHOT</version>
  </dependency>
</dependencies>

由于我们在之前通过mvn install命令将静态资源项目安装到了本地仓库,所以我们可以使用依赖。

通过IDEA工具我们可以查看webjars-sample依赖内的资源文件,如下图所示:

image

由于SpringBoot提供的spring.resources.static-locations参数默认值,会将classpath:/META-INF/resources目录作为静态资源映射,所以我们可以直接进行访问head.jpg文件。

运行SpringBoot项目,通过访问 http://localhost:8080/head.jpg,效果如下图:

image

静态资源访问前缀

我们在访问静态资源的时候并没有直接加前缀,而是通过ip:port/head.jpg直接访问,这主要是SpringBoot还提供了另外一个配置spring.mvc.static-path-pattern,其作用是用来配置静态资源的访问前缀,默认值为/**,如果需要修改直接在application.yml文件内进行赋值即可,

application.yml配置文件,如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
spring:
  application:
    name: example
  mvc:
    static-path-pattern: /static/**

我们修改了spring.mvc.static-path-pattern配置的值为/static/**,当我们重启项目后需要通过 http://localhost:8080/static/head.jpg 才可以访问到资源。

总结

如果你有一些资源不希望被别人修改,让使用者更加便利的集成时,可以采用这种方式来封装自己的webjars,只需要添加依赖引用就可以访问到静态资源,也可以将静态HTML网页通过这种方式打包。

作者个人 博客 使用开源框架 ApiBoot 助你成为Api接口服务架构师

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
spring cloud利用feign和sentinel进行内部或外部远程调用
    基于上篇讲解的Sentinel之后,这次讲讲spring cloud环境下最优雅的远程调用方式Feign
chinotan
2019/04/03
3.5K0
spring cloud利用feign和sentinel进行内部或外部远程调用
【Kotlin Spring Boot 服务端开发: 问题集锦】Spring Security 5 : There is no PasswordEncoder mapped for the id "
【Kotlin Spring Boot 服务端开发: 问题集锦】Spring Security 5 : There is no PasswordEncoder mapped for the id "null" 错误
一个会写诗的程序员
2018/08/17
6630
apollo升级1.2版本后Spring Security导致的问题
首先说下背景,博主公司有大概30多个大小应用将配置信息托管在apollo上,因公司业务复杂环境众多,导致idc的配置多达七八个,因为早期apollo(0.8.x)版本不支持idc,namespace等的管理,故今天升级了下apollo到1.2.。升级后发现有的客户端在通过config service meta接口获取接口信息的时候抛rg.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.这个异常,而有的客户端可以正常的拿到接口信息,异常详情如下:
kl博主
2023/11/18
4660
HTTP重定向到HTTPS,post请求成了GET请求 报 Required request body is missing 和 Request method GET not supported
看到: Required request body is missing 和 Request method 'GET' not supported
HaC
2020/12/30
3.8K0
HTTP重定向到HTTPS,post请求成了GET请求  报 Required request body is missing 和 Request method GET not supported
Can't convert the date-like value to string because it isn't known if it's a date (no time part), ti
报错 ERROR - 2021-05-17 15:35:22 [http-nio-8080-exec-8]freemarker.log._Log4jLoggerFactory$Log4jLogger.error(_Log4jLoggerFactory.java:59) -- Error executing FreeMarker template FreeMarker template error: Can't convert the date-like value to string because it
彼岸舞
2021/05/18
1.1K0
The consumer group[PushConsumer] has been created before, specify another name please
报错 org.apache.rocketmq.client.exception.MQClientException: The consumer group[PushConsumer] has been created before, specify another name please. See http://rocketmq.apache.org/docs/faq/ for further details. at org.apache.rocketmq.client.impl.consumer.
MickyInvQ
2020/09/27
3.4K0
jxls工具导出excel,报错:Cannot load XLS transformer. Please make sure a Transformer implementation is in cl
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163882.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/15
1.3K0
.MysqlDataTruncation: Data truncation: Data too long for column 'content' at row 1
版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/chengyuqiang/article/details/89037174
程裕强
2019/07/02
1.7K0
.MysqlDataTruncation: Data truncation: Data too long for column 'content' at row 1
【黄啊码】网友:我用kill -9终止程序,结果被辞退了
1、kill -9 id:一般不加参数kill是使用15来杀,这相当于正常停止进程,停止进程的时候会释放进程所占用的资源;他们的区别就好比电脑关机中的软关机(通过“开始”菜单选择“关机”)与硬关机(直接切断电源),虽然都能关机,但是程序所作的处理是不一样的。
黄啊码
2023/06/19
6710
【黄啊码】网友:我用kill -9终止程序,结果被辞退了
mybatis-plus DEBUG之旅
直接上报错信息 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): cn.tompro.eduservice.mapper.EduCourseMapper.getPublishCourseInfo at com.baomidou.mybatisplus.core.override.PageMapperMethod$SqlCommand.<init>(PageMapperMethod.java:2
Tom2Code
2022/11/21
4910
mybatis-plus DEBUG之旅
local class incompatible: stream classdesc serialVersionUID = 61,local class serialVersionUID = 1
序列化失败: 场景:一个JPA实体类Person 业务层使用redis缓存 一开始没有添加serialVersionUID ,使用默认的,后面改为手动指定,结果就出现序列化失败。这是因为jdk序列化会根据这个UID版本号来做一些细节处理,UID不一样的话,就无法实现反序列化了,并且将会得到InvalidClassException。 将redis中的缓存清除,后再次访问即可。 @Entity @Table(name = "tb_person") @Data @Builder @NoArgsConstruc
青山师
2023/05/05
6880
Java连接Redis时出现“ERR Client sent AUTH, but no password is set”异常的原因及解决办法
他可能只注意到 “Could not get a resource from the pool” 的报错,没有注意到下面还有一句 “ERR Client sent AUTH, but no password is set”
Li_XiaoJin
2022/06/10
2.6K0
Java连接Redis时出现“ERR Client sent AUTH, but no password is set”异常的原因及解决办法
Swagger-ui在文件上传时报错net::ERR_CONNECTION_RESET
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
yingzi_code
2019/08/30
2K0
聊聊springcloud的serviceRegistryEndpoint
本文主要研究一下springcloud的serviceRegistryEndpoint
code4it
2018/09/17
1.4K0
feign.FeignException$MethodNotAllowed: status 405 reading xxx#yyy(Integer)
使用feign 调用异常 feign.FeignException$MethodNotAllowed: status 405 reading ConsumerService#findById(Integer)
时间静止不是简史
2020/07/27
2.3K0
feign.FeignException$MethodNotAllowed: status 405 reading xxx#yyy(Integer)
Spring Cloud Config Server迁移节点或容器化带来的问题
为了说明下面的内容,我们可以先尝试重现一下问题:在一个测试环境中,将Spring Cloud Config的配置中心迁移到另外一个节点上,即配置中心的IP地址发生了变化。在完成迁移之后,我们会发现该环境下各个微服务应用的健康状态会变得时好时坏,并且在日志中会出现类似下面的报错:
程序猿DD
2018/07/31
1.3K0
Spring Cloud Config Server迁移节点或容器化带来的问题
BadSqlGrammarException:PageHelper use near 'LIMIT 50'
作为一名Java开发人员,你可能在某个深夜,面对着那令人头秃的错误日志,不禁发问:“为什么我的SQL语句总是出错?”今天,就让我们一起深入探讨这个在Java开发项目中常见的问题——org.springframework.jdbc.BadSqlGrammarException,特别是在处理Excel导入时,如何避免这个让人头疼的错误。
疯狂的KK
2025/01/16
2000
BadSqlGrammarException:PageHelper use near 'LIMIT 50'
springBoot系列教程07:异常捕获
发生异常是很正常的事,异常种类也是千奇百怪,发生异常并不可怕,只要正确的处理,并正确的返回错误信息并无大碍,如果不进行捕获或者处理,分分钟服务器宕机是很正常的事
肖哥哥
2018/08/02
9150
springBoot系列教程07:异常捕获
springboot2.0配置多数据源出错HikariPool-1 - jdbcUrl is required with driverClassName.
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
suveng
2019/09/18
3.5K0
《Springboot极简教程》MappingMongoConverter:Failed to convert from type [java.lang.String] to type [long]
Failed to convert from type [java.lang.String] to type [long] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type>
一个会写诗的程序员
2018/08/20
6470
推荐阅读
spring cloud利用feign和sentinel进行内部或外部远程调用
3.5K0
【Kotlin Spring Boot 服务端开发: 问题集锦】Spring Security 5 : There is no PasswordEncoder mapped for the id "
6630
apollo升级1.2版本后Spring Security导致的问题
4660
HTTP重定向到HTTPS,post请求成了GET请求 报 Required request body is missing 和 Request method GET not supported
3.8K0
Can't convert the date-like value to string because it isn't known if it's a date (no time part), ti
1.1K0
The consumer group[PushConsumer] has been created before, specify another name please
3.4K0
jxls工具导出excel,报错:Cannot load XLS transformer. Please make sure a Transformer implementation is in cl
1.3K0
.MysqlDataTruncation: Data truncation: Data too long for column 'content' at row 1
1.7K0
【黄啊码】网友:我用kill -9终止程序,结果被辞退了
6710
mybatis-plus DEBUG之旅
4910
local class incompatible: stream classdesc serialVersionUID = 61,local class serialVersionUID = 1
6880
Java连接Redis时出现“ERR Client sent AUTH, but no password is set”异常的原因及解决办法
2.6K0
Swagger-ui在文件上传时报错net::ERR_CONNECTION_RESET
2K0
聊聊springcloud的serviceRegistryEndpoint
1.4K0
feign.FeignException$MethodNotAllowed: status 405 reading xxx#yyy(Integer)
2.3K0
Spring Cloud Config Server迁移节点或容器化带来的问题
1.3K0
BadSqlGrammarException:PageHelper use near 'LIMIT 50'
2000
springBoot系列教程07:异常捕获
9150
springboot2.0配置多数据源出错HikariPool-1 - jdbcUrl is required with driverClassName.
3.5K0
《Springboot极简教程》MappingMongoConverter:Failed to convert from type [java.lang.String] to type [long]
6470
相关推荐
spring cloud利用feign和sentinel进行内部或外部远程调用
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验