请求转发的流程图:
具体代码:
Servlet1.java
package demo01; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用于实现请求转发 */ public class Servlet1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); System.out.println("在servlet1中查看参数:"+username); // 给材料盖个章,并传递到servlet2中查看 request.setAttribute("key1","柜台1的章"); // 请求转发必须以/打头 RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2"); requestDispatcher.forward(request,response); } }
Servlet2.java:
package demo01; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用于实现请求转发 */ public class Servlet2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); System.out.println("在servlet2中查看材料:"+username); Object key1 = request.getAttribute("key1"); System.out.println("柜台1是否有章:"+key1); //然后可以处理自己的业务 } }
最主要的是setAttribute()和getAttribute()方法
setAttribute()相当于将值作为参数绑定给request,然后再在Servlet2中获取。