RequestDispatche转发(forward)和包含(include)的区别

 

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/dispatcher3")
public class DispatcherServlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这儿的path有两种写法,第一种是不以/开头

        System.out.println("dispatcher3");
        response.getWriter().println("dispatcher3");
        //以/开头时,注意:如果执行主体是浏览器的时候,浏览器不知道当前应用的应用名是什么,所以要加
                        //如果是服务器,那么服务器知道当前应用名,则必须省略该应用名
        RequestDispatcher dispatcher = request.getRequestDispatcher("/dispatcher4");
//        dispatcher.forward(request,response);//转发  打印dispatcher4(会覆盖)
        dispatcher.include(request,response);//包含  打印dispatcher3(不会覆盖)
                                                     // dispatcher4
    }
}
=========================================================================================
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/dispatcher4")
public class DispatcherServlet4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("dispatcher4");
        response.getWriter().println("dispatcher4");
    }
}

 

你可能感兴趣的:(RequestDispatche转发(forward)和包含(include)的区别)