1.前提条件
在一次请求转发过程中,两个Servlet共享同一个请求协议包。因此两个Servlet共享这个请求协议包中请求对象和响应对象,所以在请求转发过程中两个Servlet可以通过当前请求对象实现数据共享。
当请求对象实现数据共享时使用内部attribute(ConcurrentHashMap)属性存储共享数据。
此时开发人员将请求对象称为【请求作用域对象】。
2.应用举例
2.1 代码部分
package com.songzihao.controller; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; /** * */ public class OneServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("key1","HttpServletRequest"); request.getRequestDispatcher("/two").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
package com.songzihao.controller; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; /** * */ public class TwoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String str= (String) request.getAttribute("key1"); System.out.println("TwoServlet得到的共享数据===" + str); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>OneServlet</servlet-name> <servlet-class>com.songzihao.controller.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/one</url-pattern> </servlet-mapping> <servlet> <servlet-name>TwoServlet</servlet-name> <servlet-class>com.songzihao.controller.TwoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TwoServlet</servlet-name> <url-pattern>/two</url-pattern> </servlet-mapping> </web-app>
2.2 运行结果部分