首先可以确定相对路径不需要以“/”开头,在Java web里用到的绝对路径要以“/”开头,因为“/”表示根目录(即服务器),然后“/”后面加上项目名/......
接着要考虑的关键问题是,哪里用相对路径、相对谁?,哪里用绝对路径?
很难从个例当中总结出普适的规律,所以我把自从接触Java web以来遇到的情况几乎都测试了一遍。
补充:以下为路径中所使用的几个特殊符号
.
:代表目前所在的目录,相对路径。如:<ahref="./abc">
文本</a>
或<img src="./abc" />
..
:代表上一层目录,相对路径。如:<ahref="../abc">
文本</a>
或<img src="../abc" />
../../
:代表的是上一层目录的上一层目录,相对路径。如:<imgsrc="../../abc" />
/
:代表根目录,绝对路径。如:<ahref="/abc">
文本</a>
或<img src="/abc" />
D:/abc/
:代表根目录,绝对路径。在使用相对路径时,我们用符号“.”来表示当前目录,用符号“..”来表示当前目录的父目录。
一、服务器内部某位置--->服务器内部某位置
- 服务器内部跳转,可以使用相对路径,不加项目名,不加“/”。
案例1.请求转发,开头带不带/,都可以;
有效request.getRequestDispatcher("error/error404.jsp").forward(request, response);
有效request.getRequestDispatcher("/error/error404.jsp").forward(request, response);
有效request.getRequestDispatcher("/tesyServlet").forward(request, response);
有效request.getRequestDispatcher("tesyServlet").forward(request, response);
二、客户端--->服务器内部某位置
- 客户端通过重定向、提交表单、ajax请求、超链接这几种方式向服务器发送请求时,地址栏都会显示相应的地址(地址栏有变化),可以断定这几种方式殊途同归,有同样的路径格式。
- 客户端向服务器请求数据,为确保路径不出错,最好使用绝对路径。
案例1. 重定向,注:request.getContextPath()=/visit-count
有效response.sendRedirect("tesyServlet");
有效response.sendRedirect("/visit-count/tesyServlet");
有效response.sendRedirect(request.getContextPath()+"/tesyServlet");
有效response.sendRedirect("images/haha.png");
有效response.sendRedirect("error/error404.jsp");
有效response.sendRedirect(request.getContextPath()+"/error/error404.jsp");无效response.sendRedirect("/tesyServlet");
无效response.sendRedirect("/error/error404.jsp");
案例2.src,包含项目名,则有/;不包含项目名,则无/。注:${APP_PATH }=/visit-count
有效<img alt="图片" src="images/haha.png">
有效<img alt="图片" src="${APP_PATH}/images/hahahh.png">
有效<img alt="图片" src="<%=request.getContextPath()%>/servlet/ImageServlet" />
有效<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
有效<script type="text/javascript" src="${APP_PATH}/js/jquery-2.1.1.min.js"></script>
案例3.href,包含项目名,则有/;不包含项目名,则无/。
有效<a href="error/error404.jsp">error/error404.jsp</a><br>
有效<a href="visitCount">visitCountServlet</a><br>
有效<a href="${APP_PATH}/error/error404.jsp">${APP_PATH}/error/error404.jsp</a><br>
有效<a href="${APP_PATH }/visitCountServlet">${APP_PATH }/visitCount</a><br>
有效<a href="/visit-count/visitCountServlet">/visit-count/visitCount</a><br>
无效<a href="/visitCount">/visitCountServlet</a><br>
无效<a href="/error/error404.jsp">/error/error404.jsp</a> <br>
三、其他
案例1.xml,如下。当error404.jsp显示到浏览器上时,地址栏并没有发生变化,可以推断这种情况属于服务器内部跳转,用的是相对路径,却以“/”开头,可当成特殊情况来记。
<error-page>
<error-code>500</error-code>
有效<location>/error/error404.jsp</location>
<!-- 错误<location>error/error404.jsp</location>
错误<location>/visit-count/error/error404.jsp</location>
错误<location>visit-count/error/error404.jsp</location> -->
</error-page>