Web: ServletConfig & ServletContext - 10

ServletConfig

ServletConfig概述

代表Servlet配置信息的对象。

获取ServletConfig对象

ServletConfig config = this.getServletConfig();

使用ServletConfig对象

  • 获取Servlet名称

String

getServletName()

          Returns the name of this servlet instance.

获取当前Servlet的名称

  • 获取Servlet的初始化参数

可以在<servlet>内配置<init-param>标签,为Serlvet指定一些初始化参数。

通过ServletConfig对象可以获取这些初始化参数信息,供Servlet使用。

 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.

获取ServletContext对象

ServletContext

  • ServletContext对象

代表当前web应用的对象。

在一个web应用有且仅有一个ServletContext对象。

  • ServletContext生命周期

ServletContext对象代表当前web应用。

服务器启动web应用加载到容器中,随着web应用的启动ServletContext对象被创建。

存活期间唯一的代表当前web应用。

直到服务器关闭或web应用被移除出容器,随着web应用的销毁,ServletContext对象跟着被销毁。

  • 获取ServletContext

方式一:通过ServletConfig对象获取

ServletContext sc = this.getServletConfig().getServletContext();

ServletContext sc = this.getServletContext();

方式二:通过便捷方法直接获取

  • 使用ServletContext

可以在web.xml中配置整个web应用的初始化参数

获取web应用的初始化参数

可以通过ServletContext获取web应用初始化参数

ServletContext是一个域对象

ServletContext对象是一个域对象。

ServletContext域是javaweb四大作用域之一。

api:

 void

setAttribute(String name, Object object)

          Binds an object to a given attribute name in this servlet context.

向域中写入数据

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.

获取域中所有属性名字组成的枚举

void

removeAttribute(String name)

          Removes the attribute with the given name from the servlet context.

从域中删除数据

特点

1. 生命周期

web应用启动,ServletContext对象创建,作用域开始

在web应用存活期间,一直存活

直到服务器关闭 或 web应用被移除出容器时,随着web应用的销毁,ServletContext被销毁,作用域结束

2. 作用范围

在整个web应用范围内共享数据

3. 主要功能

通过ServletContext在整个web应用范围内共享数据

  • 15
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值