今天突然被同学问到关于web的访问路径问题,很简单的他需要从一个jsp文件链接到另外的一个文件,可是一直报404
在getUserInfo.jsp中写了
test链接报404.
假如此项目是直接部署到web的ROOT目录下面的话,那么这个问题并不会出现,可是我们要想到他部署是另外的一个项目,那么也许在我们常用的http://localhost:8080/webname/index.jsp 正确的目录也许是这样 但是如果直接用 /index.jsp 的话,tomcat会默认为http://localhost:8080/index.jsp “/”对应的是tomcat的ROOT目录,所以导致访问的页面不正确,其实在很多的web项目中都会遇到一些路径问题,如何解决了?
把下面部分写到path.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("basePath",basePaht);
可以在需要的页面导入<%@ include file="/path.jsp" %>
然后采用
<a href="${basePath}/index.jsp"></a>
或者<a href="${basePath}/jsp/getUserInfo.jsp"></a>
顺便记下各种获取路径的方式:
getScheme:<%=request.getScheme() %><br/>
ContextPath:<%=request.getContextPath() %><br/>
getServerName:<%=request.getServerName() %><br/>
getServerPort:<%=request.getServerName() %><br/>
getContextPath: <%=request.getContextPath() %><br/>
getRealPath: <%=request.getSession().getServletContext().getRealPath("/WEB-INF") %><br/>
getRequestURI:<%=request.getRequestURI() %><br/>
getScheme:http
ContextPath:/webname
getServerName:localhost
getServerPort:localhost
getContextPath: /webname
getRealPath:D:\soft\Tomcat\apache-tomcat-6.0.16\webapps\webname\WEB-INF
getRequestURI:/urlDemo/jsp/test.jsp
request.getContextPath() 等同于 request.getSession().getServletContext().getContextPath()
request.getRealPath("/filename") 等同于 request.getSession().getServletContext().getRealPath("/filename")
但是request.getRealPath这个方法已经不推荐使用了。