转发与重定向的相对路径与绝对路径的问题

问题描述:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- 
页面上我们推荐使用的是绝对路径

绝对路径以/开始   
绝对路径:/经常代表从根开始.
所有在页面上的绝对路径,/都代表是从服务器的根开始  http://localhost:8080
所以在页面写绝对路径需要加上项目名

 -->
<a href="pathServlet">a链接</a><!-- 页面的相对路径都是相对于项目下开始  http://localhost:8080/java_reWeb-->
<a href="/java_reWeb/pages/b.html">b链接</a><!-- 页面的绝对路径都代表是从服务器的根开始  http://localhost:8080 -->
</body>
</html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		//相对路径是相对于项目下进行的 http://localhost:8080/java_reWeb
		//绝对路径是相对于服务器下 http://localhost:8080
		
		//重定向是浏览器重新发送请求。所以这里的绝对路径是	http://localhost:8080
		
		//成功	http://localhost:8080/java_reWeb/pathServlet
		request.getRequestDispatcher("pages/a.html").forward(request, response);
		//成功	http://localhost:8080/java_reWeb/pathServlet
		request.getRequestDispatcher("/pages/a.html").forward(request, response);
		
		//成功	http://localhost:8080/java_reWeb/pages/a.html
		response.sendRedirect("pages/a.html");
		//失败	http://localhost:8080/pages/a.html
		response.sendRedirect("/pages/a.html");
	}

解决方法:转发的话使用绝对路径和相对路径都可以,但重定向都推荐使用的是绝对路径

`转发使用绝对路径的方法`

//成功	http://localhost:8080/java_reWeb/pathServlet
//		request.getRequestDispatcher("/pages/a.html").forward(request, response);

`重定向使用绝对路径的方法`
//获取项目路径的方式有两种,一种是getServletContext().getContextPath() 另外一种是request.getContextPath()
//		String contextPath = getServletContext().getContextPath();
//		response.sendRedirect(request.getContextPath()+"/pages/a.html");
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值