日期:2014-05-16  浏览次数:20320 次

jsp&servlet相对路径总结
先定义几个替换:
http://localhost:8080/           =>  ip/
/mywar/                          =>  war/
http://localhost:8080/mywar/     =>  ip/war/
/mywar                           =>  [contextpath]  (request.getcontextpath())
总结如下:
1. 在jsp中的“/”表示的根为“ip”,不包含war路径

2. 在servlet中以forward方式使用的“/”表示的根为“ip/war/”,包含了war路径

3. 在servlet中以sendredirect方式使用的“/”表示的根为ip,不包含war路径

4. 在servlet中以forward方式跳转,则浏览器的地址栏仍然为此servlet,不会改动

5. 在servlet中以sendredirect方式跳转,则浏览器的地址栏改动为目的路径

6. 相对路径的确定是以浏览器的地址栏显示的路径为基准的,而非具体的目录结构,所以
   跳转到同目录下的某个页面使用<a href="文件名">link</a>这种方式不是永久成立的
   (做asp的人不要惊讶,这里说的jsp和servlet

7. 为了避免jsp跳jsp,servlet跳jsp,forward方式跳转,sendredirect跳转产生的路径问题, 对于jsp和使用sendredirect跳转的servlet,采用直接使用带容器路径[string request.getcontextpath()]的绝对路径就能完全解决,即:
     
<%
          string contextpath = request.getcontextpath();
          string url = contextpath + "/user/login.jsp";
       %>
       
       <a href="<%=url%>"> login</a>


    
 string contextpath = request.getcontextpath();
      string targetpath = contextpath + "/user/login.jsp";
      requestdispatcher rd = request.getrequestdispatcher(targetpath);
      rd.forward(request, response);
      ......


   对于使用forward跳转的servlet,则不要加容器路径,否则就重复出现 容器路径,原因参见 2

8. 如果使用的“../”过多也不会出现严重问题,“../”最多使链接到达“ip/”

9. 另外,在使用
      
<jsp:include page = "url" flush="true"/>
       <%@ include file="url" %>
       <%@ page errorpage = "url" %>
时, 这里url使用的“/”表示的根为“ip/war/”,包含了war路径