Spring Boot 设置项目名后静态文件相对路径问题

栏目: Java · 发布时间: 6年前

内容简介:原博客地址:server.servlet.context-path=testDemospring.mvc.static-path-pattern=/static/**

原博客地址: https://blog.csdn.net/qq_2928...

出现问题的原因

server.servlet.context-path=testDemo

spring.mvc.static-path-pattern=/static/**

定义项目名和静态资源路径后发现,templates中html 中引用的css,js的相对路径出现异常

Spring Boot 设置项目名后静态文件相对路径问题

在上面目录中,index.html 通过相对路径引用css href="../static/xxx" 就获取不到了

在没有定义 server.servlet.context-path=testDemo 的前href="../static/xxx" 这样写是没有问题的

Spring Boot 设置项目名后静态文件相对路径问题

在设置项目名后,使用相对路径的时候就会缺少项目名,从而获取不到静态资源

解决方案

  • 使用绝对路径
  • 修改路径,将href="../static/xxx" 改成href="static/xxx"
  • 使用spring thymeleaf的th:src或者th:href属性改变标签的链接路径,如
<link rel="stylesheet"  th:href="@{/pace/themes/blue/pace-theme-flash.css}>

但这3种方案,编译器无法识别路径,导致编写代码无提示,这就很难受了,下面两种方案以解决编译器无法提示的问题

  • 同样使用spring thymeleaf的th:src或者th:href,并且写的时候再加多src,href 供编译识别(推荐)
<link rel="stylesheet"  href="../static/pace/themes/blue/pace-theme-flash.css"  th:href="@{/pace/themes/blue/pace-theme-flash.css}">
  • 不使用thymeleaf或者不想每个css,js引入都多写一次路径,在html head添加<base href="XXX/">标签,这样../就不会丢失项目名,而是去掉了XXX/
<base href="XXX/">
<link rel="stylesheet"  href="../static/pace/themes/blue/pace-theme-flash.css">

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Tales from Facebook

Tales from Facebook

Daniel Miller / Polity Press / 2011-4-1 / GBP 55.00

Facebook is now used by nearly 500 million people throughout the world, many of whom spend several hours a day on this site. Once the preserve of youth, the largest increase in usage today is amongst ......一起来看看 《Tales from Facebook》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具