客户端向服务器发送请求,服务器将请求进行转发,获得响应信息,客户端只发送一次请求,地址栏信息不变。
服务器接收类,进行转发
package com.itheima.zhuanfa; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContextDemo3 extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 转发 //获得ServletContext对象 ServletContext sc=getServletContext(); System.out.println("转发前"); resp.getOutputStream().write("before".getBytes()); //获得转发器 RequestDispatcher rd=sc.getRequestDispatcher("/Demo4");//得到请求转发器 rd.forward(req,resp); /* * 转发的特点:请求的地址栏不变,两者共享request和response对象 * 转发前和转发后的页面输出都不会发送到客户端 * 转发前不要刷新response中的内容,会吧response中的内容清空 */ System.out.println("转发后"); resp.getOutputStream().write("after".getBytes()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
转发到的类把这个类的信息传到客户端
package com.itheima.zhuanfa; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContextDemo4 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getOutputStream().write("转发成功,我来自Demo4".getBytes()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }