application内置对象

application内置对象
  request 内置对象保存的属性只在当前请求有效, 经过客户端跳转之后就无效了
  session 内置对象保存的属性只在当前用户有效. 关闭浏览器就失效了.
  application 内置对象,是表示服务器范围的内置对象,关闭浏览器后属性也有效
  是多个用户共享的内置对象, 如: 要监听当前上线用户的人数, 就需要使用该对象
  application 内置对象的类型是 "javax.servlet.ServletContext".

Demo: 在 application 内置对象中保存属性

 1 @SuppressWarnings("serial")
 2 public class EmpServlet extends HttpServlet {
 3     @Override
 4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 5         //获取 application 内置对象
 6         ServletContext context = req.getServletContext();
 7         //在该内置对象中保存属性
 8         context.setAttribute("count", "在线人数是 10");
 9         //客户端跳转
10         resp.sendRedirect("/MvcPro/pages/login.jsp");
11     }
12 }

Demo: 获取项目的真实路径

 1 @SuppressWarnings("serial")
 2 public class EmpServlet extends HttpServlet {
 3     @Override
 4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 5         //获取 application 内置对象
 6         ServletContext context = req.getServletContext();
 7         //获取项目的部署路径
 8         String path = context.getRealPath("/");
 9         System.out.println(path);
10     }
11 }

 

posted @ 2019-04-22 11:04  笑长不爱笑QvQ  阅读(525)  评论(0编辑  收藏  举报