forward 和 redirect 的区别

2019-09-22  

  • 浏览器 url 地址显示不同

服务端通过 forward 返回,浏览器 url 地址不会发生变化;服务器通过 redirect 返回,浏览器会重新请求, url 地址会发生变化

 

  • 前后台两者页面跳转的处理方式不同

 forward 跳转页面,是服务端进行页面跳转加载(include)新页面,直接返回到浏览器;redirect 跳转页面,是服务端返回新的 url 地址,浏览器二次发出 url 请求

 

  • 参数携带情况不一样

forward 跳转页面,会携带请求的参数到新的页面;redirect 跳转页面,属于一次全新的 http 请求,无法携带上一次请求的参数

 

  • http 请求次数不同

forward 1次;redirect 2次

 

基于 servlet 实现

test servlet

package constxiong;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * test servlet
 * @author ConstXiong
 * @date 2019-06-26 10:00:34
 */
@WebServlet("/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public TestServlet() {
    }
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("This is test.");
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
 
}

 

请求返回

 

redirect servlet

package constxiong;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * redirect servlet
 * @author ConstXiong
 * @date 2019-06-26 10:00:34
 */
@WebServlet("/redirect")
public class RedirectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public RedirectServlet() {
    }
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("http://www.baidu.com");
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
 
}

 

请求返回

 

forward servlet

package constxiong;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * forward servlet
 * @author ConstXiong
 * @date 2019-06-26 10:00:34
 */
@WebServlet("/forward")
public class ForwardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public ForwardServlet() {
    }
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/test").forward(request, response);//forward 跳转到 test 请求
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
 
}

 

请求返回

 

ConstXiong 备案号:苏ICP备16009629号-3