-
请求转发
访问指定url路径可以到达HttpServlet的doGet方法。所以基本上全部逻辑都是写在这个方法上,这样的话,一个方法(也可以说一个Servlet)要处理的东西太多了。请求转发的目的就是把请求转发给别一个Servlet,从而分担一些任务。
1.步骤
(1)通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
(2)使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
2.示例
(1)
@WebServlet("/servletdemo1") public class ServletDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servletdemo1被访问了"); req.getRequestDispatcher("/servletdemo2").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
(2)
@WebServlet("/servletdemo2") public class ServletDemo2 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("servletdemo2被访问了"); } }
控制台输出结果:
servletdemo1被访问了
servletdemo2被访问了
3.请求转发的特点
1. 浏览器地址栏路径不发生变化
2. 只能转发到当前服务器内部资源中。
3. 转发是一次请求
-
共享数据
方法:
1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对
示例:
(1)
@WebServlet("/servletdemo1") public class ServletDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("message","Hello"); req.getRequestDispatcher("/servletdemo2").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
(2)
@WebServlet("/servletdemo2") public class ServletDemo2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object o = request.getAttribute("message"); System.out.println(o); } }
输出结果:
Hello
说明实现了共享数据。