JavaWeb——相对路径和绝对路径

绝对路径的问题:

 

1)开发时建议编写“绝对路径”:写绝对路径肯定没有问题,但写相对路径却可能会有问题。

 

在由Servlet转发到JSP页面时,此时浏览器地址栏上显示的是Servlet的路径,而若JSP页面的超链接还是相对于该JSP页面的地址,则可能会出现路径混乱的问题

 

/a.jsp

  -path

    /b.jsp

    /c.jsp

a.jsp->/Servlet -转发 ->b.jsp(有一个超链接:和b.jsp在同一路径下的c.jsp) ->无法得到页面

 

2)编写绝对路径可以避免上述问题。

 

①在JavaWeb中什么叫“绝对路径”:

  相对于当前WEB应用的根路径的路径,即任何的路径都必须带上contextPath

  http://localhost:8081/contextPath(当前WEB应用的上下文路径)/shopcart/submit.jsp √

       http://localhost:8081/a.jsp  ×

②如何编写"绝对路径":

  若/代表站点的根目录,在其前面加上contextPath就可以了,

  而contextPath可以由request或application的getContextPath()方法来获取

   <a href="/TestServlet">To B Page</a>  -->  <a href="<%= request.getContextPath()%>/TestServlet">To B Page</a>

3)JavaWeb开发中 / 到底代表什么?

 

①当前WEB应用的根路径:http://localhost:8081/contextPath/ :若/需交由Servlet容器来处理

  >请求转发时:request.getRequestDispatcher("/path/b.jsp").forward(request,response);

  >web.xml文件中映射Servlet访问路径:

  <servlet>
        <servlet-name>Step2Servlet</servlet-name>
        <servlet-class>Step2Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Step2Servlet</servlet-name>
        <url-pattern>/Step2Servlet</url-pattern>
    </servlet-mapping>

  

②WEB站点的根路径:http://localhost:8081/ :若/交由浏览器来处理

  >超链接:<a href="/TestServlet">To B Page</a>

  >表达中的action:<from action="/login.jsp">

  >做请求重定向的时候:response.sendRedirect("/a.jsp");

 

posted @ 2019-07-11 15:06  鸿森  阅读(1029)  评论(0编辑  收藏  举报