JavaWeb-03-Servlet-12-多个Servlet之间的数据共享-03HttpServletRequest接口
1.介绍
1.在同一个网站中,如果两个Servlet之间通过【请求转发】方式进行调用,那么这两个Servlet之间共享的是同一个【请求协议包】。而一个请求协议包只对应一个请求对象,所以这两个Servlet共享的是同一个【请求对象】,利用这一点可以实现数据共享。
2.在请求对象实现Servlet之间数据共享功能时,开发人员将请求对象称为【请求作用域对象】
2.命令实现
OneServlet:
public class OneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.将数据放入请求作用域对象的attribute属性中
request.setAttribute("key1",数据【任意类型】);
//2.向Tomcat申请调用TwoServlet
request.getRequestDispatcher("/two").forward(request,response);
}
}
TwoServlet:
public class TwoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从当前请求作用域对象中获取OneServlet写入的共享数据
Object 存储数据变量 = request.getAttribute("key1");
}
}
3.演示
OneServlet
package com.tsccg.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author: TSCCG
* @Date: 2021/08/20 14:08
*/
public class OneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.将数据放入请求作用域对象的attribute属性中
request.setAttribute("name","张三");
//2.向Tomcat申请调用TwoServlet
request.getRequestDispatcher("/two").forward(request,response);
}
}
TwoServlet:
package com.tsccg.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Author: TSCCG
* @Date: 2021/08/20 14:12
*/
public class TwoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从当前请求作用域对象中获取OneServlet写入的共享数据
String name = (String)request.getAttribute("name");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<center><font style=‘color:red;font-size:30px‘>TwoServlet得到了共享数据:"+ name +"</font></center>");
}
}
打开浏览器访问OneServlet:
JavaWeb-03-Servlet-12-多个Servlet之间的数据共享-03HttpServletRequest接口