Difference between include and forward mechanism for request dispatching concept?

后端 未结 4 871
执笔经年
执笔经年 2020-12-02 07:43

Forward() : This can be done in two ways by Request & ServeletContext. Forwarding a request from a servlet to another resource (servlet, JSP file, or HTML file) on th

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 08:31

    The key difference between the two is that the forward() method will CLOSE the output stream after it has been invoked, whereas the include method leaves the output stream OPEN.

    answering with an example : lets have a servlet page named xxx.java and a jsp page named yy.jsp

    In the yy.jsp

    WELCOME to yy.jsp
    

    In the xxx.java //using forward()

    RequestDispatcher rd = request.getRequestDispatcher("yy.jsp"); rd.forward(request,response); out.println("back to servlet"); //this wont b displayed

    output

    WELCOME to yy.jsp 
    

    In the xxx.java //using include()

    RequestDispatcher rd = request.getRequestDispatcher("yy.jsp"); rd.include(request,response); out.println("back to servlet");

    output

    WELCOME to yy.jsp back to servlet
    

    BUT MOST IMPORTANTLY ITS NOT ABOUT THE CONTROL, BECAUSE IF WE PUT a

    System.out.println("console output");

    after either of the .forward() or .include() invocation, the console output will get generated on each case.Its about the response to the client

    So, the basic part is if we are processing in a server side component and then forward to a JSP or Servlet in order to generate markup for a client, once that JSP or Servlet has finished processing, we can no longer call on any other components to generate markup that can be sent to the client. Once we have performed a forward, markup generation for the current request and response cycle is finished.

    Alternatively, with an include, the output stream remains open, so we can call on as many different files to generate client side markup that we need. So we can include two or three JSP files and even a Servlet in the chain of components that generate client based markup. When we use an include, the output stream is not closed after invocation.

提交回复
热议问题