一、ServletContext类
(一)、什么是ServletConfig对象
- ServletContext是一个接口
- ServletContext是一个域对象
- 一个web工程,Tomcat只会创建出一个ServletContext对象。
(二)、什么是域对象
**域对象是可以像Map集合一样存储的对象(域就是指作用范围)**这里的域对象中的域,是指保存在与对象中的数据的有效操作范围,ServletContext与对象它的数据操作有效的范围是整个Web工程。
功能 | Map集合 | 域对象 |
---|---|---|
保存数据 | put() | setAttribute() |
获取数据 | get() | getAttribute() |
(三)、ServletContext类的四个作用
- 获取在web.xml中配置的上下文参数
- 获取当前工程的工程路径
- 获取工程发布到服务器上之后,资源或目录在服务器磁盘上的句对路径。
- 可以像map一样存储数据。
(四)、实例演示
1、获取ServletContext类对象
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取ServletContext对像
// 方法一
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
// 方法二 通常都会用这种
ServletContext context1 = getServletContext();
}
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对象存储数据
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = getServletContext();
// 用setAttribute()存储数据
context.setAttribute("abc","abcValue");
// 用getAttribute()取出数据
System.out.println("从ServletContext域对象中获取数据abc的值:"+context.getAttribute("abc"));
}
二、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 | 表示请求请求跳转 |
304 | 表示客户端缓存版本是最新的 |
404 | 表示服务器已接收到请求,但是你的请求的资源不足 |
500 | 表示服务器已接收到请求,但是服务器内部错误(代码) |