域对象是可以像Map集合一样存储的对象(域就是指作用范围)这里的域对象中的域,是指保存在与对象中的数据的有效操作范围,ServletContext与对象它的数据操作有效的范围是整个Web工程。
Map集合 | 域对象 | |
保存数据 | put() | setAttribute() |
获取数据 | get() | getAttribute() |
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 // 获取ServletContext对像 3 // 方法一 4 ServletConfig config = getServletConfig(); 5 ServletContext context = config.getServletContext(); 6 // 方法二 通常都会用这种 7 ServletContext context1 = getServletContext(); 8 9 }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 创建一个ServletContext对象 ServletContext context = getServletContext(); // 获取web.xml中的配置参数<context-param> System.out.println("上下文参数url的值:"+context.getInitParameter("url")); // 获取当前工程的工程路径 System.out.println("工程路径:"+context.getContextPath()); /* * 获取工程发布到服务器上之后,资源或目录在服务器磁盘上的句对路径。 * 在getRealPath()中的参数"/"就是把路径映射到工程的WebContent文件夹下 * */ System.out.println("服务器磁盘上的绝对路径:"+context.getRealPath("/")); // 获取img中的图片 System.out.println("获取img中的图片路径:"+context.getRealPath("/img/servlet.PNG")); }
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 ServletContext context = getServletContext(); 4 // 用setAttribute()存储数据 5 context.setAttribute("abc","abcValue"); 6 // 用getAttribute()取出数据 7 System.out.println("从ServletContext域对象中获取数据abc的值:"+context.getAttribute("abc")); 8 }
200 | 表示请求成功 |
302 | 表示请求跳转 |
404 | 表示服务器已接收到请求,但是你的请求的资源不足 |
500 | 表示服务器已接收到请求,但是服务器内部错误(代码) |
原文:https://www.cnblogs.com/geq2020/p/12433896.html