共享数据:
? ? ? 域对象:一个有作用的范围的对象,可以在范围内共享数据 request域对象:代表一次请求的范围,一般用于请求转发的多个资源中共享数据 方法:
1.void setAttribute(String name,Object obj):存储数据
2.Object getAttribute(String name):通过key值获取数据
3.void removeAttribute(String name):通过key值移除数据 请求转发:一种在服务器内部的资源跳转方式
步骤:
1.通过request对象获取转发对象 RequestDispatcher getRequestDistpatcher(String path)
2.使用requestDispatcher 对象进行转发:forward(Request,Response)
@WebServlet("/requestDemo7")
public class RequestDemo7 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
System.out.println("Demo7....");
//将处理事情发送Demo8内容中去
//将数据存储request域中
request.setAttribute("msg","hello"); // msg = hello
//转发设置
RequestDispatcher requestDispatcher = request.getRequestDispatc
her("/requestDemo8");//在服务器内部进行处理过程
//将当前此次的请求和响应对象一同发送过去。
requestDispatcher.forward(request,response);
// System.out.println("Demo7已经完成转发任务....");
}
protected void doGet(HttpServletRequest request, HttpServletRespons
e response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
System.out.println("Demo8....");
//获取request域中的值
Object obj = request.getAttribute("msg");
System.out.println(obj);
}
protected void doGet(HttpServletRequest request, HttpServletRespons
e response) throws ServletException, IOException {
this.doPost(request,response);
}
}
获取ServletContext对象-- 是一个全局的存储信息的域对象,从服务器开始就创建存在的,当服务器关 闭时,对象销毁。
@WebServlet("/requestDemo9")
public class RequestDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
System.out.println(context);
context.setAttribute("name","张三");//将值存放到ServletContext
}
protected void doGet(HttpServletRequest request, HttpServletRespons
e response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/requestDemo10")
public class RequestDemo10 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
Object obj = context.getAttribute("name");
System.out.println(obj);
}
protected void doGet(HttpServletRequest request, HttpServletRespons
e response) throws ServletException, IOException {
this.doPost(request,response);
}
}
|