GET http://localhost:18086/css/all.css:浏览器无法访问项目下的静态资源
在做畅购商城项目时,浏览器无法访问项目下的静态资源,报错信息如下图所示。老师只提了一个可能原因:不能用相对路径href="./css/all.css",改为绝对路径href="/css/all.css"。 当然这只是其中之一问题,查看项目代码发现target目录下没有生成静态资源的文件夹,静态资源也就无从访问。这种问题在之前的博客也有介绍,碰到好几次了,调试bug需要耐心和积累,急躁不得。解
在做畅购商城项目时,浏览器无法访问项目下的静态资源,报错信息如下图所示。老师只提了一个可能原因:不能用相对路径href="./css/all.css"
,改为绝对路径href="/css/all.css"
。
当然这只是其中之一问题,查看项目代码发现target目录下没有生成静态资源的文件夹,静态资源也就无从访问。这种问题在之前的博客也有介绍,碰到好几次了,调试bug需要耐心和积累,急躁不得。
解决办法: 加入resources约束
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.html</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources/static</directory>
</resource>
<resources>
如下图所示,静态资源成功编译到target目录。
至此,问题还是没有解决。百度,谷歌都是类似的答案,没有解决,一晃一个下午就过去了,想死的心都有了!无奈之下,又只能用匹配大法,github上code了一个可以跑的springboot结合thymeleaf的案例,图片资源拷贝到该案例工程,可以成功运行!
比对之下发现,错误原因在于自己没有指定项目路径,项目工程无法根据href="/css/all.css"
生成静态资源的绝对路径。在application.properties配置文件中加入如下代码即可:
# Path to project 指定项目路径
project.base-dir=file:///D://project//workspace65//changgou//springboot-thymeleaf
# Templates reloading during development
spring.thymeleaf.prefix=${project.base-dir}/src/main/resources/templates/
spring.thymeleaf.cache=false
# Static resources reloading during development
spring.resources.static-locations=${project.base-dir}/src/main/resources/static/
以上为application.properties配置,可以自行转换为application.yml配置加入自己的项目中,以下是搜索web微服务application.yml完整配置。
server:
port: 18086
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:7001/eureka
instance:
prefer-ip-address: true
feign:
hystrix:
enabled: true
project.base-dir: file:///D://project//workspace65//changgou//changgou-parent//changgou-web//changgou-web-search
# Templates reloading during development
spring:
thymeleaf:
cache: false
prefix: ${project.base-dir}/src/main/resources/templates/
application:
name: search-web
main:
allow-bean-definition-overriding: true
# Static resources reloading during development
resources:
static-locations: ${project.base-dir}/src/main/resources/static/
至此,又可以愉快地撸商城项目了!
更多推荐
所有评论(0)