web开发过程中关于路径问题的总结

约束:

  1. 相对路径概念-./代表当前目录、../代表上级目录
  2. 示例的所有文件都基于http://127.0.0.1:8080/test路径开放,test为对应的contextPath

前端

  1. HTML标签的imglinkscriptform标签
  2. css文件的background属性
  3. js文件的ajax请求,这里特指Jquery插件

HTML标签

  1. img标签的src属性
    绝对路径-语法为/开头,其绝对路径是基于[scheme]://[serverName]:[port]此路径
    相对路径-语法为./或者../开头,相对的是当前html文件的路径

    示例:

    <img src="/test/info/img/1234.png",即正确的引用需要带上contextPath
    
  2. link标签的href属性
    相对路径是相对于当前html文件的路径,绝对路径是相对于[scheme]://[serverName]:[port]此路径,示例如下

<link ref="/test/css/default.css">,即也必须带上`contextPath`
  1. script标签的src属性
    此处路径约束类同link标签,示例如下
<script type="text/script" src="/test/js/default/js">  //即也必须带上contextPath
  1. form标签的action属性
    此处路径约束类同link标签,示例如下
<form action="${basePath}/info/get"></form>	//必须携带contextPath

CSS

  1. background/background-img属性
    此处路径类同HTML标签的img/link/script标签,示例如下
background:url(/test/info/img/1234.png) no-repeat center;//即必须带上contextPath

Jquery

  1. ajax请求的url路径

    • 绝对路径的写法与上述的标签写法类同,即必须带上contextPath,示例如下
    	$.ajax({
    	url:"/test/info/msg/get",
    	type:"get",
    	data:{},
    	callback:function(data){
    	}
    });
    
    • 相对路径是相相对于当前html引入文件的路径,示例如下
    test.html文件引入下述js文件,其中test.html对应的绝对路径为http://127.0.0.1:8080/test/info/msg/test.html
    <script src="/test/static/info/msg/manager.js"></script>
    $.ajax({
    	url:"list"  //请求的路径为`http://127.0.0.1:8080/test/info/msg/list`
    	//url:"./list"  //同上
    	//url:"../../info/content/get"  //请求为`http://127.0.0.1:8080/test/info/content/get`
    });
    

前台使用小结

  1. HTML标签的imglinkscriptform标签以及css文件中的background属性均遵循以下规则:
  • /开头,此路径均是相对于[scheme]://[serverName]:[port]此路径,在本文中便是http://127.0.0.1:8080,所以如果在Tomcat/Jetty这样的web容器中,倘若contextPath不为空,则务必带上contextPath属性

  • 所有的资源加载路径建议均转换为绝对路径加载,以免不必要的404错误

  1. Jqueryajax api中的url路径
  • 绝对路径的概念与第一点一致并建议使用绝对路径来进行访问,其中的contextPath可以通过前端模板视图工具,比如freemarker:<#assign basePath='${Application["basePath"]}'/>来建立全局变量

  • 相对路径的编写则需要注意
    I. html文件或者JSP页面在Tomcat/Jetty等web容器中的绝对访问路径是什么,比如spring mvc会对html页面的映射有一定的配置,所以所有的访问路径均需要转化为访问controller层的路径,即关注@Controller中的@RequestMapping()注解
    II. 在明白上述第一点的情况下,在上述绝对路径的基础上使用相对路径的规则即可

后端

这里只罗列下servlet关于路径的api以及spring mvc的路径使用

Servlet获取路径

示例路径为http://127.0.0.1:8080/test/info/msg/manager.html

  • request.getContextPath()
    返回上下文路径,此处为/test

  • request.getServletPath()
    返回servlet对应的路径,此处为/info/msg/manager.html,即不包含contextPath

  • request.getRequestURI()
    返回请求的完整路径,此处为/test/info/msg/manager.html,即包含contextPath

spring mvc的路径配置

    <!-- 静态资源映射 -->
    <mvc:resources mapping="/static/**" location="/static/"/>
     <!-- 视图配置 即对html页面的映射-->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="pages/" />
        <property name="suffix" value=".html" />
        <property name="contentType" value="text/html;charset=UTF-8" />
        <!-- 设置requestContext变量的名称 -->
        <property name="requestContextAttribute" value="request" />
        <!-- 配置是否在生成模板内容之前把HTTPsession中的数据放入model中 -->
        <property name="exposeSessionAttributes" value="true" />
        <!-- 配置是否在生成模板内容之前把HTTPrequest中的数据放入model中 -->
        <property name="exposeRequestAttributes" value="true" />
        <!-- 使用spring lib时 是否暴露 RequestContext 变量 默认为true -->
        <property name="exposeSpringMacroHelpers" value="true" />
    </bean>
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer>
        <property name="templateLoaderPath" value="/WEB-INF/views/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">utf-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>

简单看下其相关的Controller层对页面的路径映射,前台的ajax请求的相对路径便可针对此处的@RequestMapping()注解来完成相应的编写

@Controller
public class HtmlPageControl {
  @RequestMapping(value="/**/*.html")
  public void redirect(HttpServletRequest request){
    String contextPath = request.getContextPath() ;
    //设置basePath让前台获取
	if(request.getSession().getServletContext().getAttribute("basePath")==null){}
		request.getSession().getServletContext().setAttribute("basePath",contextPath) ;
	}
	//返回为**/*的模式
	String requestURI = request.getRequestURI() ;
	int start = contextPath.length() + 1;
	int end = requestURI.lastIndexOf(".html") ;
	
	return requestURI.substring(start,end) ;
   }
}

小结

  1. 此点切记:前台对于后台spring mvc需要确认html/jsp资源在其Controller层的映射,因为js文件只是被HTML/JSP文件所包含,所以ajax请求中的url属性如果采用相对路径则是针对HTML/JSP文件在Controller中的路径
  2. 前台所有的请求路径均建议使用绝对路径来完成
原文地址:https://www.cnblogs.com/question-sky/p/6890228.html