Servlet (二)

Servlet (二)

一、ServletContext类

(一)、什么是ServletConfig对象

  1. ServletContext是一个接口

  2. ServletContext是一个域对象

  3. 一个web工程,Tomcat只会创建出一个ServletContext对象。

(二)、什么是域对象

  域对象是可以像Map集合一样存储的对象(域就是指作用范围)这里的域对象中的域,是指保存在与对象中的数据的有效操作范围,ServletContext与对象它的数据操作有效的范围是整个Web工程。

  Map集合 域对象
保存数据 put() setAttribute()
获取数据 get() getAttribute()

(三)、ServletContext类的四个作用

  1. 获取在web.xml中配置的上下文参数<context-param>

  2. 获取当前工程的工程路径

  3. 获取工程发布到服务器上之后,资源或目录在服务器磁盘上的句对路径。

  4. 可以像map一样存储数据。

(四)、实例演示

  1、获取ServletContext类对象

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     }

  2、具体作用实现

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"));
    }

  4、ServletContext对象存储数据

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     }

一、

二、HTTP协议相关内容

(一)GET的请求协议

1、请求行信息

 2、请求体

 (二)POST的请求协议

1、请求行信息:

 2、请求头信息

3、请求体信息

 

(二)、响应的HTTP协议格式

(三)、页面中那些是GET请求。那些是POST请求

1、GET请求

  • 在浏览器地址栏中输入请求地址,然后敲回车
  • a标签
  • Script、link、img、iframe引入
  • form标签 method=GET

2、POST请求就只有form标签下method="post"这种状态下

(三)、常用的响应码

200 表示请求成功
302 表示请求跳转
404 表示服务器已接收到请求,但是你的请求的资源不足
500 表示服务器已接收到请求,但是服务器内部错误(代码)
原文地址:https://www.cnblogs.com/geq2020/p/12433896.html