ServletContext
来源:互联网 发布:黎明杀机怎么优化fps 编辑:程序博客网 时间:2024/06/06 14:08
1、引入
ServletContext 叫做Servlet 上下文,一个Web项目中只有一个ServletContext对象,用来表示当前Web应用环境,用来管理一个Web项目。服务器启动时创建,服务器关闭时销毁。
2、获得ServletContext对象
对于实现了Servlet接口的类,可以通过该类的对象拿到ServletConfig对象,然后通过ServletConfig对象拿到ServletContext对象。
ServletConfig config = this.getServletConfig();ServletContext sc = config.getServletContext();
对于继承了GenericServlet类的类,可以直接通过该类的对象获取ServletContext对象。
ServletContext sc = this.getServletContext();
3、ServletContext的作用
(1)、Servlet的三大域之一
ServletContext是Servlet中作用范围最大的域,作用于整个Web项目,主要用于Servlet之间共享数据。
public void servletContextTest() { ServletContext context = this.getServletContext(); //保存数据 context.setAttribute("name", object); //获取数据 context.getAttribute("name"); //清除数据 context.removeAttribute("name");}
(2)、获取当前Web项目的配置信息
配置信息应写入web.xml文件中,配置信息示例如下:
<context-param> <param-name>username</param-name> <param-value>root</param-value></context-param>
可以通过ServletContext获取web.xml中的配置信息
public void servletContextTest() { ServletContext context = this.getServletContext(); //获取初始化参数的名字列表 Enumeration<String> names = context.getInitParameterNames(); //遍历初始化参数 while(names.hasMoreElements()) { String value = context.getInitParameter(names.nextElement()); //do something with value } //根据参数名获取初始化参数的值 String initParameter = context.getInitParameter("name"); 设置初始化参数 context.setInitParameter("name", "value");}
(3)、获取Web项目中的资源
由ServletContext可以获取当前Web项目中的资源,可以拿到资源的URL或者流。
public void servletContextTest() throws MalformedURLException { ServletContext context = this.getServletContext(); //path填写相对路径,"/"相对于Web项目的根路径(WebRoot) String realPath = context.getRealPath(paht); URL url = context.getResource(paht); InputStream inputStream = context.getResourceAsStream(path);}
阅读全文
0 0
- ServletContext
- ServletContext
- servletcontext
- servletContext
- servletContext
- servletcontext
- ServletContext
- ServletContext
- servletContext
- ServletContext
- ServletContext
- servletContext
- ServletContext
- servletContext
- ServletContext
- servletContext
- ServletContext
- servletcontext
- Ruby学习笔记(19)_继承
- 解锁或者修改oracle 数据库密码
- 主流的三大分布式计算系统:Hadoop,Spark和Storm
- 最大子段和
- Android开发实践:屏幕旋转的处理
- ServletContext
- Spark性能优化之资源调优
- transformDexArchiveWithExternalLibsDexMergerForDebug unable to merge dex 问题
- System.arraycopy()方法详解
- XILINK SDK怎么使用自带串口终端
- SpringMVC默认单例的,高并发情况下,如何保证性能的?
- json序列化ipaddress类
- bzoj 1419 Red is good 【期望dp】
- 【bzoj1131】[POI2008]Sta