zoukankan      html  css  js  c++  java
  • html页面的绝对路径和相对路径

      在用springmvc架构开发网站的过程中,离不开开发前台html页面,html经常需要使用本地相关的资源,如:图片,js,css等,一般情况下,我们可以通过使用相对路径的方式来对这些资源进行指向和访问,如:

    html页面的绝对路径和相对路径 - ftutor - ftutor ops
     

     如上图的代码,可以用浏览器直接打开此处的代码,banner-graphic.png图片也能够正常显示在页面上,但是,在启动服务器时,在浏览器中打开此文件的时候,图片并不会显示。

    本系统使用mustache来完成页面的渲染,具体的viewresolver配置如下:

    <bean id="viewResolver" class="org.springframework.web.servlet.view.mustache.MustacheViewResolver">
    <property name="cache" value="false" />
    <property name="prefix" value="WEB-INF/mustache/" />
    <property name="suffix" value=".mustache" />
    <property name="templateLoader">
    <bean class="org.springframework.web.servlet.view.mustache.MustacheTemplateLoader" />
    </property>
    <property name="order" value="1" />
    </bean>

    也就是WEB-INF/mustache/ 目录下的文件可以直接通过服务器前缀访问如:http://localhost:8080/spring-mvc/login.mustache,也就是说被拦截的页面和没有被拦截的页面可能访问形式相同,但是在服务器中存放的位置有很大不同。
    虽然login.mustache不在webapp目录下面,但此时的服务器路径并非为http://localhost:8080/spring-mvc/WEB-INF/mustache/login.mustache
    而此文件中的背景图片引用为”background-image:../../images/banner-graphic.png“,图片地址自动变为http://localhost:8080/images/banner-graphic.png,显然无法显示图像,只有图片为
    http://localhost:8080/spring-mvc/images/banner-graphic.png才能够正常显示图像,故html中使用服务器端物理位置的相对路径并不能保证资源被浏览器正常访问到,解决方案如下:
    1.使用一个变量来存放服务器的路径,如:contextPath,

    public Map<String, Object> newModel(HttpServletRequest re) {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("contextPath", re.getContextPath());
    return map;
    }

    2.这个变量已经包含了服务器的根地址,所有的html页面可以使用这个统一的根地址指向,也就是webapp目录,于是所有的js,css文件就可以有唯一的定位,如:<link rel="stylesheet" type="text/css" href="{{contextPath}}/styles/login.css"/>指向的就是webapp/styles/login.css文件,{{contextPath}}可以由controller内传递出来的值解析,并且css内部的图像引用就可以自由的使用相对路径而不会出现任何报错,实例css文件:

    #head-image{
    height:75px;
    margin-bottom:0;
    background-image:url(../images/banner-graphic.png);
    }

  • 相关阅读:
    day5 元组、列表、字典和集合
    day4 字符串类型和列表类型的详细caozu
    day3 数据类型
    预习
    python基础
    计算机基础——老年人上网冲浪手册
    pycharm操作指北
    day1 计算机基础知识
    Securing a Laravel API in 20 minutes with JWTs
    Testing Api using PHPUnit Laravel
  • 原文地址:https://www.cnblogs.com/annie211/p/5995606.html
Copyright © 2011-2022 走看看