ServletContext接口

发布时间 2023-10-10 22:38:08作者: 天津天狮学院-Java
第一个ServletContext接口一个web应用创建一个,实现数据共享
步骤1.需要在web.xml中配置,写在<Web-app></web-app>中间
<param-name></param-name>写入变量名,<param-value></param-value>写入值
<context-param>
<param-name>name</param-name>
<param-value>lxh</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>lxh</param-value>
</context-param>
步骤2:在servlet里获取web.xml数据,以下代码写到Servlet中的doGet或者doPOst方法里面
//创建ServletContext变量
ServletContext context=this.getServletContext();
//得到包含所有参数化参数名的Enumeration对象
Enumeration<String> paramNames=context.getInitParameterNames();
out.println("<br/>要输出共享参数名了<br/>");
//遍历所有的初始化参数名,得到相应的参数值并打印
while(paramNames.hasMoreElements()){
String name=paramNames.nextElement();//获取名字
String value=context.getInitParameter(name);//根据名字获取值
out.println("<br/>"+name+":"+value+"<br/>");
}
第二个,多个Servlet共享数据,通过setAttribute、getAttribute等方法共享数据
 步骤1:在第一个Servlet中的doGet或doPost方法中设置数据
//创建ServletContext对象
ServletContext context=this.getServletContext();
//通过setAttribute()方法设置属性值
context.setAttribute("data","context共享数据");
 步骤2:在第二个Servlet中的doGet或doPost方法中获取
String sdata=(String)context.getAttribute("data");
第三个,获取web应用下的资源文件,比如配置文件或者图片等,文件放到src下
//Servletcontext接口定义了获取web资源方法,靠Servlet容器实现
/*
方法:getRealPath getResourcePath,getResource getResourceAsStream
*/
//获取相对路径中的输入流对象
在Servlet中的doGet或doPost方法中写入如下代码,注意:info.properties放到src下。

 PrintWriter out=response.getWriter();

InputStream in=context.getResourceAsStream("/WEB-INF/classes/info.properties");

Properties pros=new Properties();
pros.load(in);
out.println("<br/>name="+pros.getProperty("name"));
out.println("<br/>pwd="+pros.getProperty("pwd"));