今天回顾一下之前学习过的Servlet,于是乎就打算整理成博客方便以后复习巩固。本篇博客来说说Servlet四大作用域之一ServletContext.
那么,ServletContext是什么呢?
首先,ServletContext对象代表整个web应用,可以在整个web应用中达到共享数据的目的。
作为域对象,ServletContext的生命周期是:web应用被加载ServletContext对象就会被创建,web应用被移除或者服务器关闭ServletContext对象就会被销毁。可见,ServletContext对象作用范围是整个web应用。
ServletContext的主要用途有哪些呢?
- 添加属性、删除属性、获取属性值;
- 获取web的初始化信息;
- 实现请求转发;
- 获取资源;
1、 添加属性、删除属性、获取属性值;
ServletContext几个重要方法:
public Object getAttribute(String name);//取得属性值
public void setAttribute(String name, Object object);//设置属性值
public void removeAttribute(String name);//移除属性
public Enumeration getAttributeNames();//取得所有属性名字
//示例一
Servlet01代码:
//获取ServletContext对象
ServletContext context= this.getServletContext();
// this.getServletConfig().getServletContext();
context.setAttribute("name", "contex1");
String str=(String) context.getAttribute("name");
System.out.println(str); //context1
Servlet02代码:
ServletContext context=this.getServletContext();
context.removeAttribute("name");
String str=(String) context.getAttribute("name");
System.out.prin;//输出null
2、获取web的初始化信息;
再来看看ServletContext的几个重要方法
public Enumeration getInitParameterNames();//取得所有键值
public String getInitParameter(String name);//根据键名取得键值
//web初始化信息在web.xml的配置
<context-param>
<param-name>fruit</param-name>
<param-value>apple</param-value>
</context-param>
<context-param>
<param-name>vegetables</param-name>
<param-value>cabbage</param-value>
</context-param>
====================
//获取ServletContext对象
ServletContext context= this.getServletContext();
//通过键名取得fruit对应的值
String fruit= context.getInitParameter("fruit");
System.out.println("fruit="+fruit);//输出 fruit=apple
//取得全部web初始化配置信息
Enumeration<String> params=context.getInitParameterNames();
while (params.hasMoreElements()) {
String param= (String) params.nextElement();
System.out.println(param);//分别输出 fruit vegetables
}
3、实现请求转发
看一个重要相关方法:
public RequestDispatcher getRequestDispatcher(String path);
ServletContext context= this.getServletContext();
context.getRequestDispatcher("/servlet/Servlet02").forward(request, response);
4、获取资源
说说路径问题:
tomcat位置:
D:\JavaWeb\apache-tomcat-6.0.44\apache-tomcat-6.0.44
File file=new File("/1.png"); //程序从D:\1.png寻找资源
File file=new File("1.png"); //程序从D:\JavaWeb\apache-tomcat-6.0.44\apache-tomcat-6.0.44\bin\1.png
寻找资源(tomcat启动目录)
获取资源方式一:获取资源正确路径
String path=this.getServletContext().getRealPath("/2.png");
File file=new File(path);
System.out.println(file.getAbsolutePath());//输出:D:\JavaWeb\apache-tomcat-6.0.44\apache-tomcat-6.0.44\webapps\lujing\2.png
获取资源方式二:直接将资源转换成二进制流
ServletOutputStream os=response.getOutputStream();
InputStream is=this.getServletContext().getResourceAsStream("2.png");
至此,ServletContext的基本用法介绍完毕。