Web 基础 8 ServletConfig与ServletContext的简述

1.1 ServletConfig的概述

  Servlet容器初始化一个servlet对象时,会为这个servlet对象创建一个servletConfig对象。在servletConfig对象中包含了servlet的初始化参数信息。此外,servletConfig对象还与servletContext对象关联。Servlet容器在调用servlet对象的init(ServletConfig config)方法时,会把servletConfig对象当做参数传递给servlet对象。Init(ServletConfig config)方法会使得当前servlet对象与servletConfig对象建立关联关系。

  简单的说就是:servlet 容器使用的 servlet 配置对象,该对象在初始化期间将信息传递给 servlet。

1.1.1 ServletConfig的方法

方法 描述
String getInitParameter(String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.
Enumeration getInitParameterNames() Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing.
String getServletName() Returns the name of this servlet instance.

1.1.2 ServletConfig的入门案例

xml文件加入的内容

<servlet>
    <description></description>
    <display-name>Demo5Servlet</display-name>
    <servlet-name>Demo5Servlet</servlet-name>
    <servlet-class>com.itheima.servlet.Demo5Servlet</servlet-class>
    <init-param>
      <param-name>username</param-name>
      <param-value>zhangsan</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>123456</param-value>
    </init-param>
  </servlet>

注意 <init-param> 标签是 <servlet>的子标签 同时 里面的子标签是的内容类似于键值对的

程序代码

public class Demo5Servlet extends HttpServlet {
    
    /*private ServletConfig config;
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }*/
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletConfig config = getServletConfig();
        //根据初始化参数的name来获取value
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        
        
        System.out.println(username);
        System.out.println(password);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  • 在实际的作用有
    • 获取字符集编码 UTF-8
    • 获取数据库连接信息 用户名 密码 url
    • 获取配置文件

1.2 ServletContext的概述

  ServletContext是servlet与servlet容器之间的直接通信的接口。Servlet容器在启动一个Web应用时,会为它创建一个servletContext对象。每个web应用有唯一的servletContext对象。同一个web应用的所有servlet对象共享一个serveltContext,servlet对象可以通过它来访问容器中的各种资源。

  上下文对象, 他是在服务器启动的时候,会为每个web项目创建一个单独的servletContext对象,他代表了当前的WEB应用

1.2.1 ServletContext的部分方法

方法 描述
Object getAttribute(String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name.
Enumeration getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context.
ServletContext getContext(String uripath) Returns a ServletContext object that corresponds to a specified URL on the server.
String getContextPath() Returns the context path of the web application.
String getInitParameter(String name) Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.
Enumeration getInitParameterNames() Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters.
Servlet getServlet(String name) Deprecated. As of Java Servlet API 2.1, with no direct replacement.
String getServletContextName() Returns the name of this web application corresponding to this ServletContext as specified in the deployment descriptor for this web application by the display-name element.
void log(String msg) Writes the specified message to a servlet log file, usually an event log.
void removeAttribute(String name) Removes the attribute with the given name from the servlet context.
void setAttribute(String name, Object object) Binds an object to a given attribute name in this servlet context.

1.2.2 ServletContext代码功能演示

  • 获取Context对象
public class ContextDemo extends HttpServlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取ServletContext对象
       //通过ServletConfig对象来获取
       //ServletContext context = getServletConfig().getServletContext();
       
       //同过Servlet的方法来获取
       ServletContext context = getServletContext();
       
       //根据name来获取value
       String username = context.getInitParameter("username");
       String password = context.getInitParameter("password");
       
       System.out.println(username);
       System.out.println(password);
   }

   
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // TODO Auto-generated method stub
       doGet(request, response);
   }

}

  • 获取属性值

public class ContextDemo2 extends HttpServlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取ServletContext对象
       ServletContext context = getServletContext();
       //设置数据
       context.setAttribute("username", "zhangsan");
       context.setAttribute("username", "lisi");
       //获取数据
       Object obj = context.getAttribute("username");
       
       response.getWriter().println(obj);
   }

   
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // TODO Auto-generated method stub
       doGet(request, response);
   }

}

  • 获取路径

public class ContextDemo4 extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("itcast");
        
        //获取ServletContext对象
        ServletContext context = getServletContext();
        //获取当前WEB应用的绝对路径
        //String path = context.getRealPath("/WEB-INF");
        //System.out.println(path);
        
        RequestDispatcher rd = context.getRequestDispatcher("/ContextDemo2");
        //转发
        //rd.forward(request, response);
        
        //包含
        rd.include(request, response);
        
        response.getWriter().println("itheima");
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

1.3 ServletConfig与ServletContext的区别

这里推荐其他程序员的一篇博客 写的很棒

跳转地址 《ServletConfig和ServletContext的区别及应用》

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 226,197评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 97,254评论 3 410
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 173,718评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,801评论 1 305
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,732评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,200评论 1 318
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,389评论 3 433
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,484评论 0 282
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,024评论 1 328
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,013评论 3 352
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,125评论 1 359
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,698评论 5 353
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,407评论 3 342
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,795评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,996评论 1 278
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,724评论 3 384
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,150评论 2 368

推荐阅读更多精彩内容

  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,304评论 11 349
  • 目标 servlet的生命周期 servletConfig与ServletContext定义,及其二者的区别 监听...
    arkulo阅读 975评论 0 5
  • 本文包括: Servlet简介关于Servlet的一些类 Servlet生命周期 ServletConfig获得初...
    廖少少阅读 3,878评论 1 67
  • 前言 这篇文章的出发点是为了整理Servlet相关知识点,以免在相关概念混淆或分不清的时候到处查阅资料。 一、什么...
    maxwellyue阅读 3,473评论 2 35
  • 亲爱的,新的一年又来临了,外面鞭炮轰鸣,不知不觉中,您已经离开我十多年。我如今已经想不起你的形态,容貌。可忘不了你...
    wangxiangping阅读 145评论 0 1