015_请求转发和重定向

一. 重定向和转发工程

1. 新建一个SendRedirectForward的Web工程

2. 在WebContent下新建index.html和success.html

3. 编写index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>重定向和转发</title>
	</head>
	<body>
		<a href="SendRedirect.action">重定向</a><br/>
		<a href="Forward.action">转发</a>
	</body>
</html>

4. 编写success.html

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

5. 新建SendRedirect.java和Forward.java

6. 编写SendRedirect.java

package com.lywgames.myservlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirect extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.sendRedirect("success.html");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

7. 编写Forward.java

package com.lywgames.myservlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Forward extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("success.html").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

8. 编写web.xml

9. 部署运行

10. 打开chrome的开发者选项, 点击重定向

11. 打开chrome的开发者选项, 点击转发

二. 重定向和转发

1. 重定向

1.1. 重定向写法: 使用HttpServletResponse的sendRedirect方法, 参数是重定向的位, 即跳转的位置。response.sendRedirect("success.html")。

1.2. 地址栏上显示的是最后的那个资源的路径地址。

1.3. 请求次数最少有两次, 服务器在第一次请求后, 会返回302和一个地址, 浏览器在根据这个地址, 执行第二次访问。

1.4. 可以跳转到任意路径, 不是自己的工程也可以跳。

1.5. 效率稍微低一点, 执行两次请求。

1.6. 后续的请求, 没法使用上一次的request存储的数据, 或者没法使用上一次的request对象, 因为这是两次不同的请求。

2. 转发

2.1. 请求转发的写法, 参数即跳转的位置: request.getRequestDispatcher("success.html").forward(request, response);

2.2. 地址栏上显示的是请求servlet的地址, 返回200(ok)。

2.3. 请求次数只有一次, 因为是服务器内部帮客户端执行了后续的工作。

2.4. 只能跳转自己项目的资源路径 。  

2.5. 效率上稍微高一点, 因为只执行一次请求。

2.6. 可以使用上一次的request对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值