与路径相关的操作
- 超链接
- 表单
- 转发
- 包含
- 重定向
- <url-pattern>
- ServletContext获取资源
- Class获取资源
- ClassLoader获取资源
客户端路径
超链接、表单、重定向都是客户端路径,客户端路径可以分为
- 绝对路径
- 以“/”开头的相对路径
- 不以“/”开头的相对路径
例如:http://localhost:8080/hello1/pages/a.html中的超链接和表单如下:
绝对路径:<a href="http://localhost:8080/hello2/index.html">链接1</a>
相对路径1:<a href="/hello3/pages/index.html">链接2</a>
相对路径2:<a href="index.html">链接3</a>
<hr/>
绝对路径:
<form action="http://localhost:8080/hello2/index.html">
<input type="submit" value="表单1"/>
</form>
相对路径1:
<form action="/hello2/index.html">
<input type="submit" value="表单2"/>
</form>
相对路径2:
<form action="index.html">
<input type="submit" value="表单3"/>
</form>
- 链接1和表单1:没什么可说的,它使用绝对路径;
- 链接2和表单2:以“/”开头,相对主机,与当前a.html的主机相同,即最终访问的页面为http://localhost:8080/hello2/index.html;
- 链接3和表单3:不以“/”开头,相对当前页面的路径,即a.html所有路径,即最终访问的路径为:http://localhost:8080/hello1/pages/index.html;
重定向:
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("index.html");
}
}
假设访问AServlet的路径为:http://localhost:8080/hello/servlet/AServlet
因为路径不以“/”开头,所以相对当前路径,即http://localhost:8080/hello/servlet/index.html
建议使用“/”开头
在Servlet中使用request.getContextPath()来获取应用名称
response.sendRedirect(request.getContextPath() + "/BServlet");
服务器端路径
服务器端必须是相对路径,不能是绝对路径。但是相对路径有两种形式:
- 以“/”开头
- 不以“/'开头
其中请求转发、包含都是服务器端路径:
- 客户端路径以”/“开头:相对当前主机
- 服务器端路径”/'开头:相对当前应用;
以“/'开头:
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/BServlet").forward(request, response);
}
}
假设访问AServlet的路径为:http://localhost:8080/hello/servlet/AServlet
因为路径以“/”开头,所以相对当前路径,即http://localhost:8080/hello/BServlet。
不以"/"开头
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("BServlet").forward(request, response);
}
}
假设访问AServlet的路径为:http://localhost:8080/hello/servlet/AServlet
因为路径不以“/”开头,所以相对当前应用,即http://localhost:8080/hello/servlet/BServlet。
<url-pattern>路径
必须以”/“开头,并且是相对当前应用。
ServletContext获取资源、Class获取资源、ClassLoader获取资源三种方式在上一篇文章中有: