---
title: "request.getRequestDispatcher().forward() 和response.sendRedirect()区别"
author: "ethen"
date: "2010-10-28T16:00:40Z"
tags: []
categories: ["Web前端"]
slug: "request-getrequestdispatcher-forward-response-sendredirect"
draft: false
lastmod: "2010-10-28T16:04:32Z"
id: 796685
url: "https://ethen.iteye.com/blog/796685"
---

在进行请求的处理时，有两种方法进行页面转发，一种是用request.getRequestDispatcher().**forward**方法，另外一种方法是response.**sendRedirect**方法，这两种方法有什么不同呢，下面结合实例进行说明。

实例：

用户登录模块

***login.jsp***

***loginServlet.java***

***loginOK.jsp***

用户访问login.jsp，输入用户名和密码进行登录，请求到达loginServlet，loginServet中，在session中加入user属性，值为输入的用户名。接着loginServlet把请求转发给loginOK.jsp，loginOK.jsp显示用户名。

 

代码简单描述（注意颜色的对应）：

***login.jsp中：***  
username=ethen，password=pwd；

***loginServlet.java中：***  
String user=request.getParameter("username");  
session.setAttribute("user",user);

***loginOK.jsp中***:

显示request中的用户名 ${param["username"}，

显示session中的用户名 ${sessionScope\["user"]}。

 

**第一种情况：**

由loginServlet调用forward方法进行转发，首先观察浏览器的地址栏，发现了地址是形如[http://.../login.do?username](http://.../login.do?username)=..&..的样子的。页面中的request里的用户名和session的用户名都显示了出来。

 

**第二种情况：**

由loginServlet调用sendRedirect方法进行转发，还是观察地址栏，发现地址已经变成[http://.../loginOK.jsp](http://.../loginOK.jsp)了，

页面中request里面的用户名没有显示出来，但是session里的用户名却显示了出来。

这是为什么呢？

 

原来，forward 是服务器端的跳转，也就是客户端根本不知道这个动作，也就是从一个java程序，转到了另一个java程序，所以此时request会被作为参数传递过去。  
但是，sendRedirect 这个是客户端的跳转，服务器端会发送一个跳转的代码和url给浏览器，浏览器会重新请求指定的URL,所以此时，request已经无效了。当然，此时session还是生效的。

 

现在你明白了么？