javaweb绝对路径和相对路径的问题
项目结构:
在由servlet转发到jsp页面时,此时浏览器地址栏上显示的是servlet的路径,而若jsp页面的超链接还是相对于该jsp
a.jsp->/locationServlet--转发(req.getRequestDispatcher("/path/b.jsp").forward(req, resp);)-->b.jsp(有一个超链接,和b.jsp在同一个目录下的c.jsp)-->无法得到页面
使用绝对路径可以避免以上问题:
(一).绝对路径:在JavaWeb中 绝对路径是指:相对于contextPath(这里指TestTraining)的路径 ,即任何的路径都带上contextPath,开发时建议写绝对路径,写相对路径可能会出问题
绝对路径:http://localhost:8090/TestTraining/a.jsp 对
如何完成编写:若 / 代表的是站点的根目录 则在其前面加上contextPath就可以了,而contextPath可以由request.getContextPath()和application.getContextPath()方法获取
<a href="/locationServlet">to B page</a>=======><a href="<%=request.getContextPath()%>/locationServlet">to B page</a>
(二)javaWeb开发中的 "/" 代表什么意思
1.当前web应用的根路径:http://localhost:8090/TestTraining/ 需交由servlet容器来处理的
>>请求转发时: req.getRequestDispatcher("/path/b.jsp").forward(req, resp);
>>web.xml文件映射servlet访问路径:
<servlet>
<servlet-name>LocationServlet</servlet-name>
<servlet-class>com.servlet.LocationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LocationServlet</servlet-name>
<url-pattern>/locationServlet</url-pattern>
</servlet-mapping>
2.web站点的根目录:http://localhost:8090/ 交由浏览器来处理
>>超链接:<a href="b.jsp">跳转到b页面</a>
>>表单中的action:<form action="/login.jsp">
>>请求重定向的时候:response.sendRedirect();
(二)解决方案:
如果 / 代表的是站点的根目录,在其前面加上contextPath,这个contextPath可以由request或application
的getContextPath()方法来获取。
<a href="<%=request.getContextPath() %>/path/c.jsp">去CCC界面</a>
这样上面的错误就解决了。