ServletConfig
ServletConfig概述
代表Servlet配置信息的对象。
获取ServletConfig对象
ServletConfig config = this.getServletConfig(); |
使用ServletConfig对象
- 获取Servlet名称
getServletName() Returns the name of this servlet instance. 获取当前Servlet的名称 |
- 获取Servlet的初始化参数
可以在<servlet>内配置<init-param>标签,为Serlvet指定一些初始化参数。
![]() |
通过ServletConfig对象可以获取这些初始化参数信息,供Servlet使用。
getInitParameter(String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. 获取指定名称初始化信息值 | |
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. 向域中写入数据 |
getAttribute(String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name. 从域中获取数据 | |
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应用范围内共享数据