Request域和ServletContext域对象见且理解

HttpServletRequest域对象

可以临时性存放一些数据 容器

生命周期

从A服务中----->B服务中 资源跳转只能使用内部转发 再一次请求中存储数据
当一次请求结束时,在HttpServletRequest类对象中存储的数据也就消失了

request.setAttribute(String name,String value); //设置域对象的属性
request.getAttribute(String name); //获得域对象的属性
request.removeAttribute(String name); //移除域对象的属性
eg:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
    // 1. 设置字符编码集
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=UTF-8");
    // 2. 在request域中存储数据
    req.setAttribute("book1","水浒传");
    req.setAttribute("book2","西游记");
    req.setAttribute("book3","三国演义");
    req.setAttribute("book4","红楼梦");
    // 3. 资源跳转 内部转发
    req.getRequestDispatcher("/index.jsp").forward(req,resp);
    // 如果使用重定向没有数据传输
    // resp.sendRedirect("/index.jsp");
}
在jsp页面使用EL表达式    ${key}
book1:${book1}<br>
book2:${book2}<br>
book3:${book3}<br>
book4:${book4}<br>

ServletContext域对象

可以长时间的存储数据

生命周期

只要服务器不关闭,那么在该ServletContext类对象中存储的数据就永远不会消失
所以一般会把SercletContext域中存储的数据在整个web应用中共享
是因为该ServletContext类对象只有一个

存储数据
setAttribute(String name,Object obj);
获取数据
getAttribute(String name);
删除数据
removeAttribute(String name);
eg:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 获取到ServletContext域对象
    ServletContext context = req.getServletContext();
    // 往context域中存储数据
    context .setAttribute("book1","水浒传");
    context .setAttribute("book2","西游记");
    context .setAttribute("book3","三国演义");
    context .setAttribute("book4","红楼梦");
    // 3.资源跳转 跳转方式不要求
    resp.sendRedirect("/index.jsp");
}

在jsp页面使用EL表达式    ${key}
book1:${book1}<br>
book2:${book2}<br>
book3:${book3}<br>
book4:${book4}<br>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值