include与forward转发相比,包含有以下特点:
servlet1 请求转发至servlet2
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(urlPatterns = "/servlet1.do") public class Servlet1 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servlet1 service invoked"); String money = req.getParameter("money"); System.out.println("money:"+money); // 设置响应类型和编码(include模式下) /* resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8");*/ // 增加响应内容 //resp.getWriter().println("servlet1在转发之前增加的响应内容"); // 请求转发给另一个组件 // 获得一个请求转发器 //RequestDispatcher requestDispatcher = req.getRequestDispatcher("servlet2.do"); //RequestDispatcher requestDispatcher = req.getRequestDispatcher("aaa.html"); //RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp"); //RequestDispatcher requestDispatcher = req.getRequestDispatcher("WEB-INF/bbb.html"); RequestDispatcher requestDispatcher = req.getRequestDispatcher("https://www.baidu.com"); // 由请求转发器作出转发动作 requestDispatcher.forward(req,resp);// 托管给目标资源(forward多一些) //requestDispatcher.include(req,resp); // 让目标资源完成部分工作 // 继续增加响应信息 (include模式) //resp.getWriter().println("servlet1在转发之后增加的响应内容"); // 在forward转发模式下,请求应该完全交给目标资源去处理,我们在源组件中,不要作出任何的响应处理 // 在forward方法调用之后,也不要在使用req和resp对象做其他操作了 // 在include转发模式下,设置响应可以在转发之前,也可以在转发之后 } }
张三向李四借钱1000元,李四说”我也没有,要不你去王五哪里看看?”,然后张三根据李四的指示,去找王五借钱
响应重定向是通过HttpServletResponse对象sendRedirect(“路径”)的方式实现是,是服务器通知浏览器,让浏览器去自主请求其他资源的一种方式
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; import java.io.PrintWriter; @WebServlet(urlPatterns = "/servlet3.do") public class Servlet3 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servlet3 service invoked"); String money = req.getParameter("money"); System.out.println("money:"+money); // 响应重定向 resp.sendRedirect("servlet4.do?money="+money); //resp.sendRedirect("WEB-INF/bbb.html"); //resp.sendRedirect("https://www.baidu.com"); } }