ServletContext详解

原创
2014/10/15 09:54
阅读数 176

一、WEB容器在启动时候,它会为每个WEB应用程序创建一个对应的ServletContext对象,它代表当前WEB应用。
二、ServletContext对象可以通过ServletConfig.getServletContext方法获得对Servlet对象的引用,也可以通过this.getServletContext90来获得其对象的引用。
三、由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为Context域对象。公共聊天室就是用到它。
四、如何使用ServletContext?
1.如何获得ServletContext对象?
ServletContext sc=this.getServletContext();
2.可以将ServletContext想象成一张表,这个和session非常相似。
添加属性:setAttribute(String name,Object ob);
得到值:getAttribute(String name);
删除属性:removedAttribute(String name);
3.生命周期
ServletContext中的属性的生命周期从开始创建到服务器关闭而结束
五、ServletContext应用
1.可以被项目中多个servlet共享
2.获取wenb应用的初始化参数。例如:在web.xml中我们有这样一段代码,
<context-param>
    <param-name>name</param-name>
    <param-value>scott</param-value>
</context-param>
如果<context-param>和<servlet>元素是兄弟关系
String value=this.getServletContext().getInitParameter("name");
结果value的值是scott
如果<context-param>是<servlet>元素的儿子
String value=this.getServletConfig().getIn.getInitParameter("name");
结果value的值也是scott
3.可以请求转发
(1)response.sendRedirect("/web应用名/资源名");
(2)request.getRequestDispatcher("/资源名").forward(request,response)===this.getServletContext.getRequestDispatcher("/资源名").forward(request,response);
4.读取web应用的资源文件
(1)资源文件写在WebRoot下面
1>读取资源文件内容,例如:有一个msql.properties文件
文件内容如下:
username=scott
password=123
如何读取:
InputStream is=this.getServletContext().getresourceAsStream("msql.properties");//读取到文件
Propreties pp=new Propreties();
pp.load(is);
System.out.println("name="+pp.getProperty("username"));//结果是scott
2>读取文件的全路径,例如:webRoot下有一个/imgs/1.jpg文件
String Path=this.getServletContext().getRealPath("/imgs/1.jpg");
(2)资源文件在src下面则使用类加载器
随便挑选src文件下的某个类例如:Servlet.java
InputStream is=Servlet.class.getClassloader.getResourceAsStream("文件名字");

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部