到此为止:已经学习了两个域对象:
servletContext:web应用
request:仅仅用于同一个请求
作用范围:整个请求链上
生命周期:当服务器收到一个请求,创建出代表请求的request对象,request开始.当请求结束,服务器销毁代表请求的request对象,request域结束.
作用:在整个请求链范围内共享数据,通常我们在Servlet中处理好的数据会存入request域后请求转发到jsp页面来进行展示
setAttribute
getAttribute
removeAttribute
1.下面的例子既使用了域对象也使用了请求转发Demo1(在request中放了一个对象)转发到Demo2
package cn.itheima.request; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 请求转发 * @author Administrator * */ public class Demo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setAttribute("description", "李卫康--哈哈好自恋"); request.getRequestDispatcher("/servlet/Demo2").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.在Demo2中取出request域中的值并输出打印到浏览器中...
package cn.itheima.request; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String str = (String) request.getAttribute("description"); response.getWriter().write(str); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
时间: 2024-11-05 19:41:35