1. html中href
在html中经常会见到通过link和script标签引用css,js等静态文件。比如<link href="/crud/asserts/css/bootstrap.min.css" rel=“stylesheet”>。href可以写相对路径或绝对路径。通过下面的项目说明一下相对路径和绝对路径。
现在有一个springboot项目,其中一段代码如下(假设项目地址为localhost:8080/MySpringBoot)
说明一下,在springboot中,默认是到templates下找视图文件。在浏览器输入localhost:8080/MySpringBoot/emp/add,会显示addEmp.html视图。在addEmp.html中有link标签<link href=“crud/asserts/css/bootstrap.min.css” rel=“stylesheet”>,那么这个link标签中的相对路径,是相对于谁呢?最总会转换成什么样的http地址呢?
最总会转变成localhost:8080/MySpringBoot/emp/crud/asserts/css/bootstrap.min.css。因为视图addEmp.html页面是通过发起请求localhost:8080/MySpringBoot/emp/add展示的。所以视图addEmp.html中的href的相对路径,就是相对于请求路径localhost:8080/MySpringBoot/emp/add,也就是在localhost:8080/MySpringBoot/emp/下面(注意不是在add下面,和add是同级关系)。
那如果这里的link标签写成绝对路径呢?
如果写成绝对路径,也就是 <link href="/crud/asserts/css/bootstrap.min.css" rel=“stylesheet”>,最总转换成http地址就是http://localhost:8080/crud/asserts/css/bootstrap.min.css注意,这里没有项目名称,也就是说如果设置了contextpath,使用绝对路径是行不通的。
上面的情况,如果该用thymeleaf会如何呢?
如果是相对路径<link href="" th:href="@{crud/asserts/css/bootstrap.min.css}" rel=“stylesheet”>,最总转换的跟不用thymeleaf一样,结果也是http://localhost:8080/MySpring/emp/crud/asserts/css/bootstrap.min.css。
如果是绝对路径,就是正常的,结果是http://localhost:8080/MySpring/crud/asserts/css/bootstrap.min.css