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>