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()不同,因为它们的实际发布路径变了。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值