---Jsp(三)转发和重定向

来源:互联网 发布:迪杰斯特拉算法 动画 编辑:程序博客网 时间:2024/06/02 13:09

转发和重定向

转发的过程是服务器使用一个内部的方法来调用目标页面,继续处理同一个请求,浏览器并不知道这个过程,

重定向是服务器通知浏览器再发一个新的请求,再来处理这个新的请求

这个过程中,转发:浏览器总共发了一次请求;重定向:浏览器总共发了两次请求。当使用重定向时,浏览器中所显示的URL会变成新页面的URL, 而当使用转发时,该URL会保持不变。重定向的速度比转发慢,因为浏览器还得发出一个新的请求。同时,由于重定向方式产生了一个新的请求,所以经过一次重 定向后,request内的对象将无法使用。

区别:
重定向:以前的request中存放的变量全部失效,并进入一个新的request作用域。
转发:以前的request中存放的变量不会失效,就像把两个页面拼到了一起。

代码:
test.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>    <a href="forwardServlet">Foward</a>    <br>    <br>    <a href="redirectServlet">Redirect </a></body></html>

ForwardServlet.java

public class ForwardServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        System.out.println("forwardServlet's doGet...");        // 请求的转发        // 调用httpservletrequest的getRequestDispatch方法获取RequestDispatch对象,需要传入转发的地址        String path = "testServlet";        RequestDispatcher dispatcher = request.getRequestDispatcher("/" + path);        // 调用dispatch的forward方法,转发请求        dispatcher.forward(request, response);    }}

RedirectServlet.java

public class RedirectServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 请求的重定向,        // 直接调用response的sendRedirect(),传入位置        String location = "testServlet";        response.sendRedirect(location);    }}

TestServlet.java

public class TestServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        System.out.println("testServlet's doGet...");    }}

理解:
点击Forward后,控制打印;forwardServlet’s doGet… testServlet’s doGet…,
浏览器地址栏为http://localhost:8080/WebApp4/forwardServlet
通过chrome开发者工具看到这个过程中只有一个请求。

点击Redirect后,控制台打印:testServlet’s doGet…
浏览器地址栏为:http://localhost:8080/WebApp4/testServlet
通过chrome开发者工具看到这个过程有两个请求。

转发和重定向的区别在于,在转发整个过程中,浏览器只发出了一次请求,在重定向的这个过程中,浏览器总共发出了两次请求。对于转发可以看到转发的时候传入了当前的参数request和response,而在重定向的时候,只是指明了location,这一点也可以证明转发是使用当前的request到新的Servlet去处理请求,而重定向是重新发一次请求到新的Servlet再来处理请求。

0 0
原创粉丝点击