转发与重定向的区别

196 阅读1分钟

结论

先说结论

  • 转发
request.getRequestDispatcher("/路径").forward(request, response)

1、只能转发到同一个Context下,路径中不用包含ContextPath 2、客户端只发了一次请求 3、浏览器地址栏的URL不会发生变化 4、转发的操作只由服务器完成

  • 重定向
response.sendRedirect("/路径")

1、可以重定向到任意URL,如果重定向到同一个Context下,路径中需要包含ContextPath 2、客户端发了两次请求 3、浏览器地址栏的URL会发生变化 4、重定向的操作由服务器+客户端配合完成

转发

代码举例:"/test1"转发到"/test2"再转发到"/test3"

test1:

@WebServlet("/test1")
public class test1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

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

        req.setAttribute("name", "jack");

        System.out.println("test1Request"+req);

        req.getRequestDispatcher("/test2").forward(req,resp);


    }
}

test2:

@WebServlet("/test2")
public class test2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

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

        System.out.println("test2Request"+req);

        req.getRequestDispatcher("/test3").forward(req,resp);

    }
}

test3:

@WebServlet("/test3")
public class test3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

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

        System.out.println("test3Request"+req);

    }
}

image.png

image.png

  • 源码

image.png

image.png

重定向

resp.sendRedirect("/hello/list");

image.png

  • 源码在Response.javasendRedirect

image.png

设置302状态码和location. `