java web中的各种servlet路径

一直搞不懂web中各种复杂的路径,直到现在还是觉得很杂乱,此文稍微列举一些方法得到的路径。

request.getServletContext()得到的是ServletContext对象,getRealPath(“/”) 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径。

例如:我的tmall项目是在E:\project\tmall。

我在tomcat的servlet.xml中配置context:

<Context path="/tmall" docBase="E:\\project\\tmall\\web" debug="0" reloadable="false" />

path是访问此项目的虚拟路径根目录;docBase是此项目绝对路径,如果Web应用采用开放目录结构,则指定Web应用的根目录。docBase也是项目的发布目录。

在web目录下的test目录下,创建一个el.jsp文件:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<style>
    th{
        color: red;
    }

</style>
<head>
    <title>练习</title>
</head>
<body>
<table border="1px" style="border-collapse: collapse ">
    <tr>
        <th>request.getServletContext():</th>
        <td><%=request.getServletContext()%></td>
    </tr>
    <tr>
        <th>request.getServletContext().getRealPath("/"):</th>
        <td><%=request.getServletContext().getRealPath("/")%></td>
    </tr>
    <tr>
        <th>request.getServletContext().getRealPath("helloworld"):</th>
        <td><%=request.getServletContext().getRealPath("helloworld")%></td>
    </tr>
    <tr>
        <th>request.getContextPath()</th>
        <td><%=request.getContextPath()%></td>
    </tr>
    <tr>
        <th>request.getServletPath()</th>
        <td><%=request.getServletPath()%></td>
    </tr>
    <tr>
        <th>request.getRequestURL()</th>
        <td><%=request.getRequestURL()%></td>
    </tr>
    <tr>
        <th>request.getRequestURI()</th>
        <td><%=request.getRequestURI()%></td>
    </tr>
</table>


</body>
</html>

启动tomcat,运行结果:

关闭tomcat,在idea中启动它的Tomcat,运行结果:

可以看到只有getRealPath()不同,因为它们的实际发布路径变了。

猜你喜欢

转载自blog.csdn.net/linghuainian/article/details/82227177