- 域对象:一个有作用范围的对象,可以在范围内共享数据
* request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
* 方法:
1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对
@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//存储数据到request域中
request.setAttribute(“msg”,“hello”);
request.getRequestDispatcher("/requestDemo9").forward(request,response);
//request.getRequestDispatcher(“http://www.itcast.cn”).forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/requestDemo9")
public class RequestDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取数据
Object msg = request.getAttribute("msg");
System.out.println(msg);
System.out.println("demo9999被访问了。。。");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
共享数据
1. setAttribute(String name,Object value)
2. getAttribute(String name)
3. removeAttribute(String name)
* ServletContext对象范围:所有用户所有请求的数据
*
1. 通过HttpServlet获取
ServletContext context = this.getServletContext();
//设置数据
context.setAttribute(“msg”,“haha”);
2. 通过HttpServlet获取
ServletContext context = this.getServletContext();
//获取数据
Object msg = context.getAttribute(“msg”);
System.out.println(msg);