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的区别及应用》

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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