首页 > 其他 > 详细

Servlet (二)

时间:2020-03-11 19:25:25      阅读:59      评论:0      收藏:0      [点我收藏+]

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 表示服务器已接收到请求,但是服务器内部错误(代码)

Servlet (二)

原文:https://www.cnblogs.com/geq2020/p/12433896.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!